我正在制作一个包含HTML请求的基本iPhone应用,方法是按照 this tutorial.
本教程让我在AFNetworking中使用AFJSONRequestOperation。麻烦的是,我正在使用AFNetworking版本2,它不再具有AFJSONRequestOperation。
因此,当然,这段代码(从教程的大约一半开始,在“查询iTunes Store Search 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?我用谷歌搜索了这一点,发现似乎没有其他人在问这个问题。
答案 0 :(得分:30)
你能使用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
}];
答案 1 :(得分:7)
来自NSHipster's article on AFNetworking 2:
AFNetworking 2.0新架构的突破之一是使用序列化器来创建请求和解析响应。灵活的串行器设计允许将更多业务逻辑传输到网络层,并且可以轻松定制以前内置的默认行为。
在AFNetworking 2中,序列化程序(将HTTP数据转换为可用的Objective C对象的对象)现在是请求操作对象的独立对象。
AFJSONRequestOperation等因此不再存在。
来自the AFJSONResponseSerializer docs:
AFJSONResponseSerializer
是AFHTTPResponseSerializer
的子类,用于验证和解码JSON响应。
有几种方法可以点击你提到的API。这是一个:
NSURL *url = [[NSURL alloc] initWithString:@"http://itunes.apple.com/search?term=harry&country=us&entity=movie"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success: %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
}];
[operation start];