【问题标题】:sendAsynchronousRequest deprecated in iOS 9在 iOS 9 中不推荐使用 sendAsynchronousRequest
【发布时间】:2024-01-10 00:17:01
【问题描述】:

我正在尝试将我的代码从 Swift 1.2 更改为 Swift 2.0,但我遇到了一些关于“sendAsynchronousRequest”的问题,因为它总是显示警告,因为它已被弃用。我已经尝试使用这篇文章中的另一个解决方案:Cannot invoke 'sendAsynchronousRequest' in Swift 2 with an argument list,但它仍然无法正常工作,并且我再次收到相同的警告。

我必须在我的代码中进行哪些更改才能解决此警告?警告如下:

sendAsynchronousRequest 在 iOS 9 中被弃用,使用 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

}

【问题讨论】:

  • 所以你想抑制警告或者你想移动到dataTaskWithRequest:completionHandler
  • 嗨@Wain,我想把它改正,所以如果这是正确的,我宁愿取消警告。提前致谢。
  • 抑制已弃用方法的警告不是一个好主意。只需按照警告建议使用 NSURLSession 即可。
  • 正确的意思是升级到新的 API,因为已弃用的 API 现在已经过时,将来将不再支持和删除
  • 对不起,我不会为你写代码。阅读文档,亲自尝试,如果仍有问题,请提出具体问题。

标签: ios swift2 ios9


【解决方案1】:

正如警告警告的那样,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()

【讨论】:

  • 感谢您的快速示例@Keller,我已经从您的代码中更改了一些内容,现在它可以在没有警告的情况下运行。非常感谢。
  • 你能告诉我凯勒如何在得到 web 服务的响应后通过字典来 pushviewcontroller 吗?
  • 要么向视图控制器的初始化程序添加字典参数,要么如果您使用情节提要转场,请将字典保存在属性中并在 prepareForSegue 中设置。您还应该确保将视图控制器推送到主线程。
【解决方案2】:

使用NSURLSession 代替如下,

对于 Objective-C

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

  }] resume];

对于斯威夫特,

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

【讨论】: