Ios 使用NSURLSession检查连接响应
由于IOS 9.0中不推荐使用NSURLConnection,它说从现在起我必须使用NSURLSession。不过我需要一些帮助。我对委托使用NSURLConnection只是为了检查URL是否给出响应。如何使用NSURLSession执行此操作 我的代码:Ios 使用NSURLSession检查连接响应,ios,Ios,由于IOS 9.0中不推荐使用NSURLConnection,它说从现在起我必须使用NSURLSession。不过我需要一些帮助。我对委托使用NSURLConnection只是为了检查URL是否给出响应。如何使用NSURLSession执行此操作 我的代码: NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"HEAD"]; NSURLC
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSURLConnection *connection;
connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([(NSHTTPURLResponse *)response statusCode] == 200) {
//Do Things
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//Do other things
}
谢谢大家! 最简单的方法是使用
NSURLSession
的完成块格式副本。这样,您可以享受可取消的异步请求,但无需编写任何委托方法。如果您不需要会话中的任何特殊功能(例如自定义缓存或类似功能),您可以使用sharedSession
,它可以避免您创建和配置NSURLSession
:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
// check status code here
}
if (error) {
// handle other errors here
}
// handle data here
}];
[task resume];