sendSynchronousRequest在ios 9中已弃用

Xcode说sendSynchronousRequest已经被弃用了。

我应该如何replace它?

 let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let postLength:NSString = String( postData.length ) let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var response: NSURLResponse? var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch _ as NSError { urlData = nil } catch { fatalError() } 

这是一个工作的例子,你应该使用NSURLSession和Request。

  func testPost(sender: UIButton) { let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" let d = "4" let data = "x=4&y=\(d)" request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding) let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in if let error = error { print(error) } if let data = data{ print("data =\(data)") } if let response = response { print("url = \(response.URL!)") print("response = \(response)") let httpResponse = response as! NSHTTPURLResponse print("response code = \(httpResponse.statusCode)") //if you response is json do the following do{ let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) let arrayJSON = resultJSON as! NSArray for value in arrayJSON{ let dicValue = value as! NSDictionary for (key, value) in dicValue { print("key = \(key)") print("value = \(value)") } } }catch _{ print("Received not-well-formatted JSON") } } }) task.resume() } 

请注意,没有必要使用该请求。 你可以有一个URL的数据任务,但我添加了请求,因为在你的代码中,你已经在请求中设置了一些头。

注意使用completionHandler ,当你的服务器通过http响应来响应的时候会调用它。