52

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.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Dom Bryan
  • 1,238
  • 2
  • 19
  • 39
  • 1
    I thought NSURLConnection was deprecated in iOS8. You should be using NSURLSession since iOS7. – Fogmeister Jun 19 '15 at 10:02
  • What's the issue? Do you have trouble understanding [the documentation](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/dataTaskWithRequest:completionHandler:)? – DarkDust Jun 19 '15 at 10:02
  • Yes, I do not know how to convert this to use dataTaskWtihReqeust, I do not know what I need to change. – Dom Bryan Jun 19 '15 at 10:03
  • I agree with DarkDust, NSURSession is pretty straight forward to understand. Take a look at Ray's tutorial http://www.raywenderlich.com/51127/nsurlsession-tutorial – Josip B. Jun 19 '15 at 10:06
  • 3
    Patronizing me won't help how ever, I am new to swift and prefer to see answers then have eureka moments when I see what you did. I will take a look however this is Objectvice-C, know of any tutorials in swift? – Dom Bryan Jun 19 '15 at 10:10
  • You've been answering Swift questions for half a year now. Really, you need to learn to read the documentation, it's all there. That's a soft skill you will need as a developer. Your method already has all the types you need to make the call to `dataTaskWithRequest`, all you need to do is replace replace the call of `NSURLConnection.sendAsynchronousRequest` with the call of `NSURLSession.sharedSession.dataTaskWithRequest`. It doesn't get much easier. – DarkDust Jun 19 '15 at 10:15
  • Please search SO, here is great answer to your Swift need: http://stackoverflow.com/questions/24040893/how-to-use-nsurlsessiondatatask-in-swift – Josip B. Jun 19 '15 at 10:16
  • Thank you for the answers, plus @DarkDust I appreciate where you are coming from, and I will correct myself, I am amateur, I may have been doing it for half a year but for half and hour a week, practically a beginner. I was simply referring to the "Oh Come on", it seemed unnecessary for you to help me with my search. – Dom Bryan Jun 19 '15 at 10:19
  • You're right, my tone was unnecessary, sorry about that. I just believe this issue is so simple that you should (no, _must_) be able to solve it yourself and that you'll learn a bigger lesson solving it yourself. In the 20mins this discussion is going on you should have been able to find the solution :-) (Plus, the solution can already be found on SO already, as @JosipB. pointed out.) – DarkDust Jun 19 '15 at 10:24
  • @DarkDust well thank you for the time taken to help me, I shall take note for next time I need to figure something out. – Dom Bryan Jun 19 '15 at 10:27

10 Answers10

85

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.

Nilesh Patel
  • 6,318
  • 1
  • 26
  • 40
16

Swift implementation

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

}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Ankit Sachan
  • 7,690
  • 16
  • 63
  • 98
  • 8
    Don't forget you need to call `resume()` on your `dataTaskWithRequest` or it won't do anything. – memmons Feb 07 '16 at 17:01
10

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()
karma
  • 1,282
  • 18
  • 23
9

This is the swift 2.1 version:

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

Swift 2.0:

Old (replace with New below):

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

// Code

}

New:

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

// Code

}
task.resume()
Elliott Davies
  • 833
  • 9
  • 6
3

Swift 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()
Haroldo Gondim
  • 7,725
  • 9
  • 43
  • 62
1

with swift 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()
Imtee
  • 1,345
  • 13
  • 14
0

Illustrating with an example, the alternative code to the deprecation of:

sendAsynchronousRequest(_:queue:completionHandler:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]

Tested and works in Swift 2.1 onwards.

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

    }

}

//Displays an image on the ViewControllers ImageView. Connect an outlet of the ImageView

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Naishta
  • 11,885
  • 4
  • 72
  • 54
0

Here is the SWIFT3.0 Version of Nilesh Patel's Answer with JSONSerialised data

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)
            }
Community
  • 1
  • 1
Vatsal Shukla
  • 1,274
  • 12
  • 25
0

Swift 4.2

This worked for me:

func loadImageFromURL(URL: NSURL) {
    let request = URLRequest(url: URL as URL)
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let imageData = data {
            DispatchQueue.main.async {
                self.imageView.image = UIImage(data: imageData)
            }
        }
    }
    task.resume()
}

I had to add "DispatchQueue.main.async { }" because I had a runtime warning, since only the main thread is supposed to modify UI elements.

Michele Dall'Agata
  • 1,474
  • 2
  • 15
  • 25