不推荐使用iOS9 sendSynchronousRequest

问题描述:


警告:iOS 9.0中不推荐使用'sendSynchronousRequest(_:returningResponse :)'
:使用[NSURLSession dataTaskWithRequest:completionHandler:]
(参见NSURLSession)

Warning:'sendSynchronousRequest(_:returningResponse:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession)



urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)

有关如何摆脱此警告的任何想法?我刚从Swift 1.2升级到Swift 2

Any idea on how to get rid of this warning? I just upgraded from Swift 1.2 to Swift 2

更新:Fonix被标记为我的最佳答案。如果您尝试添加try语句,我修改了他的答案如下:

UPDATE: Fonix is marked as my best answer. If your trying to add a try statement, I modified his answer as followed:

urlData = try NSURLSession.dataTaskWithRequest(<#request: NSURLRequest#>, completionHandler: <#((NSData!, NSURLResponse!, NSError!) -> Void)?##(NSData!, NSURLResponse!, NSError!) -> Void#>)


使用 NSURLSession 而不是如下,

对于Objective-C

For Objective-C

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

  }] resume];

对于Swift,

var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["username":"username", "password":"password"] as Dictionary<String, String>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    println("Response: \(response)")})

task.resume()