Search code examples
iosswiftios9

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


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.


Solution

  • 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.