Search code examples
iosswift2ios9

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

}

Solution

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