Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用NSURLSession检查连接响应_Ios - Fatal编程技术网

Ios 使用NSURLSession检查连接响应

Ios 使用NSURLSession检查连接响应,ios,Ios,由于IOS 9.0中不推荐使用NSURLConnection,它说从现在起我必须使用NSURLSession。不过我需要一些帮助。我对委托使用NSURLConnection只是为了检查URL是否给出响应。如何使用NSURLSession执行此操作 我的代码: NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"HEAD"]; NSURLC

由于IOS 9.0中不推荐使用NSURLConnection,它说从现在起我必须使用NSURLSession。不过我需要一些帮助。我对委托使用NSURLConnection只是为了检查URL是否给出响应。如何使用NSURLSession执行此操作

我的代码:

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];