在 AFNetworking 中替换 dataWithContentsOfURL

Posted

技术标签:

【中文标题】在 AFNetworking 中替换 dataWithContentsOfURL【英文标题】:Replacement of dataWithContentsOfURL in AFNetworking 【发布时间】:2014-07-22 06:32:27 【问题描述】:

我在here 中发现你永远不应该使用dataWithContentsOfURL

我是 AFNetworking 的新手。使用 AFNetworking 替换 dataWithContentsOfURL 的正确(也是最简单)方法是什么?比如如何替换:

NSData *data = [NSData dataWithContentsOfURL:url];

【问题讨论】:

【参考方案1】:

抱歉,这有点晚了,但我认为这就是您要找的东西(感谢AFNetworking ReadMe on Github):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) 
     NSLog(@"JSON: %@", responseObject);
 failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     NSLog(@"Error: %@", error);
];

然后,如果需要,您可以使用 (source) 将 responseData 转换为 NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:responseObject];

【讨论】:

以上是关于在 AFNetworking 中替换 dataWithContentsOfURL的主要内容,如果未能解决你的问题,请参考以下文章