如何在AFNetworking 2中执行AFHTTPRequestOperation

时间:2016-08-07 18:36:55

标签: ios objective-c afnetworking afnetworking-2 afnetworking-3

我在以前的一些应用程序中使用AFNetworking多次实现了JSON解析:

    NSString *string = [NSString stringWithFormat:@"%@?get_all_data", BaseURLString];
        NSURL *url = [NSURL URLWithString:string];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
//performing parsing here

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//error message displayed here
}

但截至今天,我开始研究应用程序一段时间后我再次使用AFNetworking并使用pods安装,因此我编写了相同的代码,因为我用它来编写它之前给我一个错误说Unknown Receiver AFHTTPRequestOperation. Do you mean AFHTTPRequestSerializer?
在搜索之后,我发现现在是AFNetworking 23时代,他们已经以某种方式改变了场景。我现在没有找到关于如何实现它的确切解决方案。因此,任何人都可以在下面的答案中编写代码,该代码适用于最新版本的AFNetworking

1 个答案:

答案 0 :(得分:2)

这是AFNetworking 3.x解析数据的新方法:

NSString *path = @"yourapilink";
NSString *escapedPath = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager GET:escapedPath  parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

希望有所帮助!