NSURLSession代表与完成Handler [英] NSURLSession delegate vs. completionHandler

查看:226
本文介绍了NSURLSession代表与完成Handler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用完成处理程序。使用 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 协议。



使用以下方法:



NSURLSessionDataDelegate - 获取请求的连续状态


(NSURLSession *)会话dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse :( NSURLResponse *)响应
completionHandler:(void( ^)(NSURLSessionResponseDisposition处置))completionHandler {

receivedData = nil; receivedData = [[NSMutableData alloc] init];
[receivedData setLength:0];

completionHandler(NSURLSessionResponseAllow);
}



NSURLSessionDataDelegate



<$ p $($)$($)$($)$($)$($)$($)$($)$ :数据];
}



NSURLSessionTaskDelegate



<$ p $($)$($)$($)$($)$($)$ {code $ c $ $ b //处理错误
}
else {
NSDictionary * response =(NSDictionary *)[NSJSONSerialization JSONObjectWithData:receivedData选项:kNilOptions错误:& tempError];
//执行NSDictionary响应的操作
}

如果你想将代理代码(中间层)从您的呼叫类中分离出来(通常它的良好做法有单独的类/网络呼叫层),NSURLSession的代表必须是: -

  NSURLSession * session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:myCustomDelegateClass delegateQueue:nil]; 

参考链接:


  1. NSURLSession类参考

  2. iOS NSURLSession示例(HTTP GET,POST,Background Downlads)

  3. 从NSURLConnection到NSURLSession


I've always used completion handlers. With NSURLConnection and now with NSURLSession. It's led to my code being really untidy, especially I have request within request within request.

I wanted to try using delegates in NSURLSession to implement something I've done untidily with NSURLConnection.

So I created a NSURLSession, and created a 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];

Right now I have a completionHandler for the response, how would I switch to delegates to manage the response and data? And can I add another dataTask from the delegate of this one? Using the cookies that this dataTask created and placed into the session?

解决方案

If you want to add a custom delegate class, you need to implement the NSURLSessionDataDelegate and NSURLSessionTaskDelegate protocols at the minimum.

With the methods:

NSURLSessionDataDelegate - get continuous status of your request

 - (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);
}

NSURLSessionDataDelegate

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
   didReceiveData:(NSData *)data {

    [receivedData appendData:data];
}

NSURLSessionTaskDelegate

 - (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
}

If you want to separate the delegate code (middle layer) from your calling class (generally its good practice to have separate class/layer for network calls), the delegate of NSURLSession has to be :-

NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:myCustomDelegateClass delegateQueue:nil];

Ref Links:

  1. NSURLSession Class Reference
  2. iOS NSURLSession Example (HTTP GET, POST, Background Downlads )
  3. From NSURLConnection to NSURLSession

这篇关于NSURLSession代表与完成Handler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆