【发布时间】: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 现在已经过时,将来将不再支持和删除
-
对不起,我不会为你写代码。阅读文档,亲自尝试,如果仍有问题,请提出具体问题。