我通过遵循this tutorial.来制作带有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?我在Google上搜索了一下,发现似乎没有其他人在问这个问题。
最佳答案
您可以使用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
}];
关于ios - 在AFNetworking 2.x中替换AFJSONRequestOperation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21294178/