iphone - AFNetworking (AFJSONRequestOperation) 转换为 AFHTTPClient

标签 iphone afnetworking

我有以下运行良好的代码,但我需要对其进行更多控制,尤其需要在 0.9 中开始使用 Reachability 代码。

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”。

最佳答案

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

+ (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方法

[[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]); 
      }];

关于iphone - AFNetworking (AFJSONRequestOperation) 转换为 AFHTTPClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9411364/

相关文章:

ios - 需要帮助从 iOS 设备上传多个大图像

ios - 附加到多部分表单的断言失败

objective-c - Swift 和 AFNetworking 集成

ios - 使用 AFNetworking 从 Django 服务器下载文件

iphone - iOS 4 在应用程序处于后台时使用 GPS 定期更新位置

iphone - 如何将推送通知从一台 iPhone 设备发送到另一台?

iphone - 在使用 CGContext 绘制的 UIImage 中获取触摸

ios - 使用 AFHTTPRequestOperation Manager 时响应失败

javascript - 从 UIWebview 中删除图像

iphone - YouTube 是否破坏了 iPhone 上嵌入的 IFrame?