How to use completion block using SDWebImage in Swift 3.0?

后端 未结 5 1467
孤城傲影
孤城傲影 2021-01-04 12:35

Am using SDWebImage to download image. I want to do further operation if image is downloaded successfully.

cell.appIcon.sd_setImage(with: url, placeholderIma         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 12:58

    According to the typedef in the framework you're using:

    typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
    

    an SDExternalCompletionBlock consists of optional parameters as indicated by _Nullable. Therefor your code should be written like this:

    cell.appIcon.sd_setImage(with: url, placeholderImage: UIImage.init(named: "App-Default"), completed: {(image: UIImage?, error: NSError?, cacheType: SDImageCacheType, imageURL: URL?) -> Void in
          // Perform operation. 
    })
    

    Since the compiler knows the types of the completion block's parameters (from the function declaration) you can write the code more succinctly and (IMO) easier to read like this:

    cell.appIcon.sd_setImage(with: url, placeholderImage: UIImage(named: "App-Default"), completed: { (image, error, cacheType, imageURL) in
          // Perform operation. 
    })
    

提交回复
热议问题