在AFNetworking 2.x中替换AFJSONRequestOperation

 小老虎颖儿 发布于 2023-02-01 00:20

按照本教程,我正在制作一个带有HTML请求的基本iPhone应用程序.

本教程让我在AFNetworking中使用AFJSONRequestOperation.问题是,我正在使用AFNetworking版本2,它不再具有AFJSONRequestOperation.

所以,当然,这个代码(从教程的大约一半,在" 查询iTunes Store搜索API " 标题下)不编译:

NSURL *url = [[NSURL alloc]
    initWithString:
    @"http://itunes.apple.com/search?term=harry&country=us&entity=movie"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"%@", JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
        NSError *error, id JSON) {
            NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];
[operation start];

我的问题是,我该如何替换AFJSONRequestOperation以便我可以继续使用AFNetworking 2.x?我用谷歌搜索了这一点,发现似乎没有其他人在问这个问题.

1 个回答
  • 你能用AFHTTPSessionManger吗?所以像

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager GET:[url absoluteString]
      parameters:nil
         success:^(NSURLSessionDataTask *task, id responseObject) {
             NSLog(@"JSON: %@", responseObject);
         }
         failure:^(NSURLSessionDataTask *task, NSError *error) {
            // Handle failure
         }];
    

    另一种选择可能是使用AFHTTPRequestOperation并再次设置responseSerializer [AFJSONResponseSerializer serializer].所以像

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] 
                                                initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation
                                                            , id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // Handle error
    }];
    

    2023-02-01 00:59 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有