我一直使用补全处理程序。随着NSURLConnection
现在有了NSURLSession
。这导致我的代码非常混乱,尤其是我在请求中有请求。
我想尝试使用委托NSURLSession
来实现我已经完成的工作NSURLConnection
。
因此,我创建了一个NSURLSession
,并创建了一个dataTask
:
NSURLSessionDataTask *dataTask = [overallSession dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}];
[dataTask resume];
现在我有一个completionHandler
响应,我将如何切换到代表来管理响应和数据?我可以dataTask
从这个代表中添加另一个吗?使用由此dataTask
创建并放置在会话中的cookie ?
如果要添加自定义委托类,则至少需要实现NSURLSessionDataDelegate
和NSURLSessionTaskDelegate
协议。
用的方法:
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
receivedData=nil; receivedData=[[NSMutableData alloc] init];
[receivedData setLength:0];
completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
if (error) {
// Handle error
}
else {
NSDictionary* response=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
// perform operations for the NSDictionary response
}
如果您要将委托代码(中间层)与调用类分开(通常的优良作法是为网络调用提供单独的类/层),则NSURLSession的委托必须为:-
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:myCustomDelegateClass delegateQueue:nil];
参考链接:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句