Jordi Gámez
Jordi Gámez

Reputation: 3544

sendAsynchronousRequest deprecated in iOS 9

I'm trying to change my code from Swift 1.2 to Swift 2.0 but I'm having some problems regarding the "sendAsynchronousRequest" because it's always showing a warning because it's deprecated. I have tried using another solution from this post: Cannot invoke 'sendAsynchronousRequest' in Swift 2 with an argument list but it's still not working and I'm having the same warning again.

What I have to change in my code to solve this warning? The warning is the following:

sendAsynchronousRequest was deprecated in iOS 9, use dataTaskWithRequest:completionHandler

This is my code:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // try to reuse cell
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MarcaCollectionViewCell

    // get the deal image
    let currentImage = marcas[indexPath.row].imagen
    let unwrappedImage = currentImage
    var image = self.imageCache[unwrappedImage]
    let imageUrl = NSURL(string: marcas[indexPath.row].imagen)

    // reset reused cell image to placeholder
    cell.marcaImageView.image = UIImage(named: "")

    // async image
    if image == nil {

        let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
            if error == nil {

                image = UIImage(data: data!)

                self.imageCache[unwrappedImage] = image
                dispatch_async(dispatch_get_main_queue(), {
                    cell.marcaImageView.image = image

                })
            }
            else {

            }
        })
    }

    else {
        cell.marcaImageView.image = image
    }

    return cell

}

Upvotes: 3

Views: 5244

Answers (2)

Nilesh Patel
Nilesh Patel

Reputation: 6394

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>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    println("Response: \(response)")})

task.resume()

Upvotes: 1

Keller
Keller

Reputation: 17081

As the warning warns, NSURLConnection is dead. Long live NSURLSession.

let session = NSURLSession.sharedSession()
let urlString = "https://api.yoursecureapiservergoeshere.com/1/whatever"
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
  print("done, error: \(error)")
}
dataTask.resume()

Upvotes: 10

Related Questions