iOS 9中不推荐使用sendAsynchronousRequest

时间:2015-09-28 15:03:26

标签: ios swift2 ios9

我试图将我的代码从Swift 1.2更改为Swift 2.0,但我遇到了关于" sendAsynchronousRequest"的问题。因为它已被弃用,所以它始终显示警告。我尝试过使用此帖子中的其他解决方案:Cannot invoke 'sendAsynchronousRequest' in Swift 2 with an argument list但它仍然无效,我再次收到相同的警告。

我必须在代码中更改以解决此警告?警告如下:

在iOS 9中不推荐使用

sendAsynchronousRequest,使用dataTaskWithRequest:completionHandler

这是我的代码:

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

}

2 个答案:

答案 0 :(得分:10)

警告警告,NSURLConnection已经死亡。 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()

答案 1 :(得分:1)

使用NSURLSession代替如下,

对于Objective-C

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] resume];

对于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()
相关问题