用 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的主要内容,如果未能解决你的问题,请参考以下文章
iOS开发 GETPOST请求方法:NSURLSession篇