如何在Swift 3.0中使用SDWebImage完成块?

我使用SDWebImage下载图像。 如果成功下载图像,我想进一步操作。

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

但是我收到了错误:

无法将类型’(UIImage!,NSError!,SDImageCacheType,URL!) – > Void’的值转换为预期的参数类型’SDExternalCompletionBlock?’

终于解决了。

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

SWIFT 4版本

 cell.appIcon.sd_setImage(with: url, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { image, error, cacheType, imageURL in // your rest code }) 

重要! 在必要时,不要忘记将自我发送为弱或无主(如此[自我弱] / [自己未拥有])到块,以避免保留周期。

例:

 cell.appIcon.sd_setImage( with: url, placeholderImage: UIImage(named: "App-Default"), options: SDWebImageOptions(rawValue: 0), completed: { [self weak] image, error, cacheType, imageURL in guard let selfNotNil = self else { return } // your rest code } ) 

根据你正在使用的框架中的typedef

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

SDExternalCompletionBlock_Nullable指示的可选参数组成。 因此,您的代码应该像这样写:

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

由于编译器知道完成块参数的类型(来自函数声明),您可以更简洁地编写代码,并且(IMO)更容易阅读,如下所示:

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

这个也适用于swift 3:

 cell.appIcon.sd_setImage(with: url, placeholderImage: UIImage(named: "App-Default"), options: []) { (image, error, imageCacheType, imageUrl) in // Perform your operations here. } 
 cell.appIcon.sd_setImage(with: url, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (img, err, cacheType, imgURL) in // code }) 

试试这个,希望这会很好