用 NSUrlSession 替换 NSUrlConnection

Posted

技术标签:

【中文标题】用 NSUrlSession 替换 NSUrlConnection【英文标题】:Replace NSUrlConnection with NSUrlSession 【发布时间】:2017-03-15 10:07:14 【问题描述】:

您好,我有一个使用 NSurlConnection 的项目,我只想用 NSUrlSession 替换它。以下是代码。请帮助您进行更改。

- (IBAction)getResponse:(id)sender

    [status setText:@"Retrieving response async"];
    [response setText:@""];

    NSURL *requestUrl = [[NSURL alloc] initWithString:url.text];
    NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];


- (void)connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response

    NSLog(@"Response recieved");


- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data

    NSLog(@"Data recieved");
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [response setText:responseString];
    [status setText:@"Response retrieved async"];


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge


【问题讨论】:

【参考方案1】:

试试这个

   [[[NSURLSession sharedSession]dataTaskWithRequest:request 
  completionHandler:^(NSData * _Nullable data, NSURLResponse * 
  _Nullable response, NSError * _Nullable connectionError) 
   //Handle your response
   ] resume];

【讨论】:

以上是关于用 NSUrlSession 替换 NSUrlConnection的主要内容,如果未能解决你的问题,请参考以下文章

NSURLSession学习

iOS开发 GETPOST请求方法:NSURLSession篇

NSURLSession的GET和POST请求的封装

NSURLSessionDownloadTask - 在 didFinishDownloading 之前读取下载的数据

NSURLSession -- 实际开发中运用

应用重启后监控 NSURLSession