Search code examples
iosswift2nsurlconnectiondeprecatednsurl

sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code?


I'm using XCode 7.3. Here is my code:

func postToServerFunction() {
    let url: NSURL = NSURL(string: "http://mytesturl.com")!
    let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
    //let textfeld = String(UserTextField.text)
    let bodyData = "data=" + UserTextField.text!
    request.HTTPMethod = "POST"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
        (response, data, error) in}}

This works fine and my php-Script gets the string it should. But there is the sendAsynchronousRequest was deprecated in iOS 9 message. As I read, with Swift 2 the method has changed. I searched a lot for this error, but I'm not able to convert the code that it matches to Swift 2. As I also read, i should use something like this

let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)

but I can't get it down. And actually, I don't understand every single line. I wrote the code myself, but from some examples that it works for me.


Solution

  • This is the most basic way you'd use a shared session:

    if let url = NSURL(string: "http://mytesturl.com"),
           userField = UserTextField.text {
    
        let request = NSMutableURLRequest(URL: url)
        let bodyData = "data=" + userField
        request.HTTPMethod = "POST"
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
    
        let session = NSURLSession.sharedSession()
    
        let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
    
    
            }
        )
    
        dataTask.resume()
    }
    

    For more detail on the other approaches including background and ephemeral sessions, as well as how to handle the NUSRLResponse, see my blogpost.