I saw a lot of tutorials with a specific URL to download image but I have optional URL which would come from API and in image downloading function Xcode ask me to force-unwrap which i can't do.
cell.coverView?.image = downloader(StringURLFromAPI)
and in downloader function
func downloader(url: String?) -> UIImage {
let data = NSData(contentsOfURL: NSURL(string: url))
return UIImage(data: data)
}
TIA :)
It's better to make your downloader
function return optional. It should return UIImage only if the NSURL and NSData objects were successfully created:
func downloader(url: String?) -> UIImage? {
guard let url = url,
let imageUrl = NSURL(string: url),
let data = NSData(contentsOfURL: imageUrl)
else { return nil }
return UIImage(data: data)
}
You can also check out this library for downloading images from remote urls: https://github.com/rs/SDWebImage
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.