Claire
Claire

Reputation: 37

iOS-Swift 3-SDWebImage

I updated my code from Swift 2 to Swift 3 and I found the error of 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
                    }
                }
            }

The definition of SDWebImageCompletionWithFinishedBlock is the following

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

The error message is

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

Can anyone help me how to solve this error? Thanks.

Upvotes: 0

Views: 4195

Answers (1)

Sajjon
Sajjon

Reputation: 9907

The signature for the completion block is this:

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

You need to make the following changes:

  1. Change NSError to Error.
  2. Change NSURL to URL
  3. Change ! to ?

Using that you can write a method like this:

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

That you use like this:

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

Upvotes: 2

Related Questions