【发布时间】:2016-10-27 01:43:59
【问题描述】:
我有类似实现 NSURLConnectionDelegate 方法的服务 API 类。我注意到其中一些方法已被弃用,Apple 现在建议使用 NSURLSession。我创建了这个服务 API 自己的委托,调用类将实现该委托,并在收到响应时执行该委托。我正在寻找在使用 NSURLSession 时如何做类似的事情。
我现在使用 NSURLConnection 的东西:
@class ServiceAPI;
@protocol ServiceAPIDelegate <NSObject>
- (void)getResponseData:(NSData *)responseData;
@end
@interface ServiceAPI : NSObject<NSURLCoDelegate>
- (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest;
@property (nonatomic, weak) id <ServiceAPIDelegate> delegate;
@end
在 ServiceAPI 实现文件中:
- (void)httpServiceRequest:(NSMutableURLRequest *)serviceRequest {
//[[NSURLSession sharedSession] dataTaskWithRequest:serviceRequest] resume];
self.requestConnection = [NSURLConnection connectionWithRequest:serviceRequest delegate:self];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.delegate getResponseData:self.responseData sender:self];
}
类发出请求并获得响应:
@interface CallingController : UITableViewController<ServiceAPIDelegate>
@end
实现文件 CallingController:
- (void)getResponseData:(NSData *)responseData {
// Do something with response.
}
在使用 NSURLSession 时,如何让调用类像 NSURLConnection 一样处理响应方法。在阅读 NSURLSession 时,看起来请求和响应是使用完成处理程序一起处理的,如下所示:
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
}];
我仍然想要一个服务 API 类,我的控制器只会将请求传递给服务 API 以进行调用,一旦响应返回,它将被传递给控制器。如何在使用 NSURLSession 时将响应传递给控制器。
【问题讨论】:
标签: ios nsurlconnection nsurlsession