gpt4 book ai didi

iphone - 使用 AFJSONRequestOperation 返回 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:31:25 26 4
gpt4 key购买 nike

我已经实现了 AFNetworking 框架,但是我试图找出一种在单独的类中使用 AFJSONRequestOperation 函数并从我的个人 View Controller 调用它的方法。

我所做的是创建一个类方法,它采用字典中的参数和 web 服务 url。我希望这能够从成功 block 返回 JSON 数组和 Http 代码,但这不起作用。

如果我将公共(public)函数更改为具有返回类型并在方法末尾返回一个值,它会在成功 block 完成之前返回。

有什么建议吗?

+ (void)RequestJSON:(NSDictionary *)params:(NSString *)webServicePath {

NSURL *url = [NSURL URLWithString:@"http://api.website.com/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:webServicePath parameters:params];
NSLog(@"%@", request);

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{

NSString *httpCode = [[JSON valueForKey:@"meta"]valueForKey:@"code"];
NSLog(@"code=%@", httpCode);

}

failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(@"Failed: %@",[error localizedDescription]);

}];
[operation start];

}

最佳答案

根据其他用户的推荐,我最终创建了自己的委托(delegate),它在成功和失败方法中执行两个选择器 didReceiveJSON 和 didNotReceiveJSON。

编辑:这是我的代码:)

JSONRequest.h

#import <Foundation/Foundation.h>

@class JSONRequest;

@protocol JSONRequest <NSObject>

- (void)didReceiveJSONResponse:(NSDictionary*)JSONResponse;
- (void)didNotReceiveJSONResponse;

@end

@interface JSONRequest : NSObject {

id <JSONRequest> delegate;
}

@property (strong, nonatomic) id <JSONRequest> delegate;

- (void)RequestJSON:(NSDictionary* )params:(NSString*)webServicePath;

@end

JSONRequest.m

#import "JSONRequest.h"
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"

@implementation JSONRequest
@synthesize delegate;

- (void)RequestJSON:(NSDictionary *)params:(NSString *)webServicePath {

NSURL *url = [NSURL URLWithString:@"http://api.mysite.com"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:webServicePath parameters:params];
NSLog(@"%@", request);

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSDictionary *jsonDictionary = JSON;
[delegate performSelector:@selector(didReceiveJSONResponse:) withObject:jsonDictionary];
}

failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(@"Failed: %@",[error localizedDescription]);
[delegate performSelector:@selector(didNotReceiveJSONResponse)];

}];
[operation start];

}

@结束

关于iphone - 使用 AFJSONRequestOperation 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13763937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com