Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sendAsynchronousRequest was deprecated in iOS 9, How to alter code to fix

Tags:

ios

ios9

swift

Below is my code I am getting the issue with:

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()         }     } } 

This is now deprecated as of iOS 9, and is telling me to use dataTaskWithRequest instead. Can someone help me change sendAsync with dataTask, I don't know how to.

like image 967
Dom Bryan Avatar asked Jun 19 '15 10:06

Dom Bryan


2 Answers

Use NSURLSession instead like below,

For Objective-C

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

For 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() 

For asynchronously query, from Apple docs

Like most networking APIs, the NSURLSession API is highly asynchronous. It returns data in one of two ways, depending on the methods you call:

To a completion handler block that returns data to your app when a transfer finishes successfully or with an error.

By calling methods on your custom delegate as the data is received.

By calling methods on your custom delegate when download to a file is complete.

like image 185
Nilesh Patel Avatar answered Sep 20 '22 13:09

Nilesh Patel


Swift implementation

let session = NSURLSession.sharedSession() session.dataTaskWithRequest(request) { (data, response, error) -> Void in  } 
like image 43
Ankit Sachan Avatar answered Sep 22 '22 13:09

Ankit Sachan