对成员数据任务的模糊引用(with:completionHandler :)

时间:2017-12-25 06:39:38

标签: ios swift3 nsurlsession

为什么我的完成处理程序出现问题,如何解决此问题?

func loadImageusingCacheWithUrlString(urlString: String) {

    self.image = nil
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
        self.image = cachedImage
        return
    }

    let url = NSURL(string : urlString)

    URLSession.shared.dataTask(with: url!,
                               completionHandler: { (data, response, error) in
        if error != nil {
            print(error!)
            return
        }
        DispatchQueue.main.async(execute: {
            if let currImage = UIImage(data: data) {
                imageCache.setObject(currImage, forKey: urlString)
                self.image = currImage
            }

            //cell.imageView?.image = UIImage(data: data)
        })

    }).resume()

}

1 个答案:

答案 0 :(得分:1)

使用此

let url = URL(string : urlString)

此外,您可能会收到错误“可选类型的数据'数据?'没有打开“,所以你应该写:

if let currImage = UIImage(data: data!) {
     imageCache.setObject(currImage, forKey: urlString)
     self.image = currImage
}