sendSynchronousRequest:returningResponse:error: - What shall I use now?

sendSynchronousRequest:returningResponse:error: - What shall I use now?

我现在用什么代替NSURLConnection's

sendSynchronousRequest:returningResponse:error:

在 iOS 9 ?


sendAsynchronousRequest 已在 iOS 9 中弃用。
ObjC

 NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] ]; 

Swift

let session = NSURLSession.sharedSession()
        session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    }

您必须创建一个 NSMutableURLRequest 对象并指定您的 URL 和 HTTP 方法。

注意:您还可以创建一个委托 class 并添加一个 NSURLSessionDataDelegate 协议来接收响应,而不是将所有网络代码添加到UI class 是的。
tutorial1 tutorial2