ios NSURLSession 委托 vs. completionHandler

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22653182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:49:36  来源:igfitidea点击:

NSURLSession delegate vs. completionHandler

iosobjective-cdelegatesnsurlconnectionnsurlsession

提问by AndrewSB

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

我一直使用完成处理程序。随着NSURLConnection和现在NSURLSession。这导致我的代码真的很乱,尤其是我在请求中请求中。

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

我想尝试使用委托NSURLSession来实现我用NSURLConnection.

So I created a NSURLSession, and created a dataTask:

所以我创建了一个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];

Right now I have a completionHandlerfor the response, how would I switch to delegates to manage the response and data? And can I add another dataTaskfrom the delegate of this one? Using the cookies that this dataTaskcreated and placed into the session?

现在我有一个completionHandler响应,我将如何切换到代表来管理响应和数据?我可以dataTask从这个代表中添加另一个吗?使用它dataTask创建并放置到会话中的 cookie ?

回答by Vacca

If you want to add a custom delegate class, you need to implement the NSURLSessionDataDelegateand NSURLSessionTaskDelegateprotocols at the minimum.

如果要添加自定义委托类,至少需要实现NSURLSessionDataDelegateNSURLSessionTaskDelegate协议。

With the methods:

使用方法:

NSURLSessionDataDelegate - get continuous status of your request

NSURLSessionDataDelegate - 获取请求的连续状态

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

NSURLSessionDataDelegate

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

    [receivedData appendData:data];
}

NSURLSessionTaskDelegate

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 的委托必须是:-

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
  1. NSURLSession 类参考
  2. iOS NSURLSession 示例(HTTP GET、POST、背景下载)
  3. 从 NSURLConnection 到 NSURLSession