首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AFNetworking (AFJSONRequestOperation)转换为AFHTTPClient

AFNetworking (AFJSONRequestOperation)转换为AFHTTPClient
EN

Stack Overflow用户
提问于 2012-02-23 18:39:23
回答 1查看 7.3K关注 0票数 5

我有以下代码,可以很好地工作,但我需要对它进行更多的控制,尤其需要开始使用0.9中的可达性代码。

代码语言:javascript
复制
NSString *urlString = [NSString stringWithFormat:@"http://example.com/API/api.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    _self.mainDictionary = [JSON valueForKeyPath:@"elements"];
    [_self parseLiveData];
} failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
    //NSLog(@"Failed: %@",[error localizedDescription]);        
}];

if (operation !=nil && ([self.sharedQueue operationCount] == 0)) {
    [self.sharedQueue  addOperation:operation];
}

我正在努力研究如何将相同的代码转换为使用AFHTTPClient,这样我就可以利用"setReachabilityStatusChangeBlock“。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-27 19:00:15

只需使用单例创建AFHTTPClient的子类

代码语言:javascript
复制
+ (id)sharedHTTPClient
{
    static dispatch_once_t pred = 0;
    __strong static id __httpClient = nil;
    dispatch_once(&pred, ^{
        __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://example.com/API"]];
        [__httpClient setParameterEncoding:AFJSONParameterEncoding];
        [__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    });
    return __httpClient;
}

然后调用getPath方法

代码语言:javascript
复制
[[YourHTTPClient sharedHTTPClient]
   getPath:@"api.php"
   parameters:nil
      success:^(AFHTTPRequestOperation *operation, id JSON){
              _self.mainDictionary = [JSON valueForKeyPath:@"elements"];
              [_self parseLiveData];
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          //NSLog(@"Failed: %@",[error localizedDescription]); 
      }];
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9411364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档