iOS-Swift 3-SDWebImage

iOS-Swift 3-SDWebImage

我将我的代码从 Swift 2 更新为 Swift 3,我发现了 SDWebImage 的错误。

SDWebImageManager.shared().downloadImage(with: URL(string: book.picURL), options: .lowPriority, progress: { (min:Int, max:Int) -> Void in

            }) { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, finished:Bool, url:NSURL!) -> Void in
                if image != nil && finished
                {

                    let obj = cell.keepUrl
                    if obj != nil && url != nil && obj == url
                    {
                        cell.picURL.image = image
                    }
                }
            }

SDWebImageCompletionWithFinishedBlock的定义如下

typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);

错误信息是

"Cannot convert value of type '(UIImage!, NSError!, SDImageCacheType, Bool, NSURL!) -> Void' to expected argument type 'SDWebImageCompletionWithFinishedBlock!'"

谁能帮我解决这个错误?谢谢。

完成块的签名是这样的:

typealias PrefetchingDone = (UIImage?, Error?, SDImageCacheType, Bool, URL?) -> Void

您需要进行以下更改

  1. NSError 更改为 Error
  2. NSURL更改为URL
  3. !更改为?

使用它你可以编写这样的方法:

class func preloadImageWithUrlString(_ urlString: String, fetchedClosure: ImageFetchedClosure? = nil) {
    let imageURLString = addWidthParameter(urlString, width: width)
    guard let url = URL(string: imageURLString) else { 
        // Call closure with some error...
        fetchedClosure(nil, MyError.someCustomErrorHere, SDImageCacheTypeNone, true, nil)
        return
    }

    SDWebImageManager.shared().downloadImage(with: url, options: SDWebImageOptions(rawValue: 0), progress: nil) { 
        (maybeImage, maybeError, cacheType, finished, imageURL) in
        if let closure = completionClosure {
            closure(maybeImage, maybeError, cacheType, url)
        }
    }
}

你这样使用:

UIImageView.preloadImageWithUrlString("http://some.url.com/myImage.png") { 
    (maybeImage, maybeError, cacheType, finished, imageURL) in
    print("prefetching done")
}