sendAsynchronousRequest在iOS 9中已被弃用,如何修改要修复的代码

下面是我的代码我遇到的问题:

func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void) { NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in if ((error) != nil) { callback(feed: nil, error: error) } else { self.callbackClosure = callback let parser : NSXMLParser = NSXMLParser(data: data!) parser.delegate = self parser.shouldResolveExternalEntities = false parser.parse() } } } 

现在已经不推荐使用iOS 9了,而是告诉我使用dataTaskWithRequest。 有人可以帮我改变sendAsync与dataTask,我不知道如何。

像下面这样使用NSURLSession

对于Objective-C

 NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"] 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> request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in print("Response: \(response)")}) task.resume() 

用于从Apple 文档进行asynchronous查询

像大多数networkingAPI一样,NSURLSession API是高度asynchronous的。 它以两种方式之一返回数据,具体取决于您调用的方法:

当传输成功完成或发生错误时,将数据返回到应用程序的完成处理程序块。

通过在收到数据时调用自定义委托的方法。

下载到文件完成时,通过调用自定义委托上的方法。

Swift实现

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

这是迅速的2.1版本:

 let request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" let params = ["username":"username", "password":"password"] as Dictionary<String, String> request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in print("Response: \(response)")}) task.resume() 

Swift 3.0

 var request = URLRequest(url: URL(string: "http://example.com")!) request.httpMethod = "POST" let session = URLSession.shared session.dataTask(with: request) {data, response, err in print("Entered the completionHandler") }.resume() 

Swift 2.0:

旧的(用下面的Newreplace):

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response, data, error) -> Void in // Code } 

新:

 let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in // Code } task.resume() 

迅速3.1

 let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL) let session = URLSession.shared request.httpMethod = "POST" let params = ["username":"username", "password":"password"] as Dictionary<String, String> request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in print("Response: \(String(describing: response))")}) task.resume() 

举一个例子来说明,弃用的替代代码:

sendAsynchronousRequest(_:queue:completionHandler :)'在iOS 9.0中已被弃用:使用[NSURLSession dataTaskWithRequest:completionHandler:]

testing和工作在Swift 2.1以上。

 import UIKit class ViewController: UIViewController { @IBOutlet var theImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in if error != nil { print("thers an error in the log") } else { dispatch_async(dispatch_get_main_queue()) { let image = UIImage(data: data!) self.theImage.image = image } } } task.resume() } } 

//在ViewControllers ImageView上显示图像。 连接ImageView的sockets

这里是JSONSerialised数据的Nilesh Patel答案的SWIFT3.0版本

 let url = URL(string: "<HERE GOES SERVER API>")! var request = URLRequest(url: url) request.httpMethod = "POST" //GET OR DELETE etc.... request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("<ValueforAuthorization>", forHTTPHeaderField: "Authorization") let parameter = [String:Any]() //This is your parameters [String:Any] do { let jsonData = try JSONSerialization.data(withJSONObject: parameter, options: .prettyPrinted) // here "jsonData" is the dictionary encoded in JSON data request.httpBody = jsonData let session = URLSession(configuration: .default) let task = session.dataTask(with: request, completionHandler: { (incomingData, response, error) in if let error = error { print(error.localizedDescription) print(request) }else if let response = response { print(response) }else if let incomingData = incomingData { print(incomingData) } }) task.resume() } catch { print(error.localizedDescription) } 

斯威夫特4

 let params = ["email":"email@email.com", "password":"123456"] as Dictionary<String, String> var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!) request.httpMethod = "POST" request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in do { let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject> print(json) } catch { print("error") } }) task.resume()