简体   繁体   中英

How to use pass nil to URL in SDWebImage with Swift

I am using SDWebImage function in a Swift controller.

sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;

in swift it is displaying as

let url  = NSURL(string:ventModel.backgroundBlurredURL)
let img = UIImage(named: "")
cell.courseImgView.sd_setImageWithURL(url, placeholderImage: img) { (UIImage img, NSError err, SDImageCacheType cacheType, NSURL imgUrl) -> Void in

    }

Now lets say in my model ie ventModel I cannot get a imageURL ie nil. So the app will give a fatal error and crashes.

You should declare backgroundBlurredURL as optional like

var backgroundBlurredURL: String?

and then unwrap your url:

if let url  = NSURL(string:ventModel.backgroundBlurredURL) {
   let img = UIImage(named: "")
   cell.courseImgView.sd_setImageWithURL(url, placeholderImage: img) {
       (UIImage img, NSError err, SDImageCacheType cacheType, NSURL imgUrl) -> Void in
            // Do awesome things
       }
}

backgroundBlurredURL will not be set in case server doesn't send data for it.

Update:

If it's in objective C, then you can directly check for backgroundBlurredURL != nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM