我正在尝试使用SDWebImage从外部URL下载图像并返回它。我不想在视图上设置它。这是我正在使用的代码,但是没有用。我要归零。但是我知道我要传递的网址有效,因为我可以在浏览器中看到它。我究竟做错了什么?
func downloadImage() -> CGImage {
var myImage: CGImage?
let myUrl = URL(string: "my-url-here.com")
SDWebImageDownloader.shared.downloadImage(with: myUrl, completed: { (image, data, error, true) in
print("Completed")
if image != nil {
myImage = image?.cgImage
}
})
return myImage!
}
我也尝试过这个版本,也没有运气:
func downloadImage() -> CGImage {
var myImage: CGImage?
let myUrl = URL(string: "my-url-here.com")
SDWebImageManager.shared.loadImage(with: myUrl, options: .continueInBackground, progress: { (received, expected, nil) in
print(received, expected)
}, completed: { (downloadedImage, data, error, SDImageCacheType, true, imageUrlString) in
DispatchQueue.main.async {
if downloadedImage != nil {
myImage = downloadedImage?.cgImage
}
}
})
return myImage!
}
SDWebImage是一个异步库。您不能只是return
结果。通常,将使用@escaping
闭包将结果提供给调用方。例如
func downloadImage(completion: @escaping(CGImage?) -> Void) {
let url = URL(string: "https://my-url-here.com")!
SDWebImageDownloader.shared.downloadImage(with: url) { image, _, _, _ in
completion(image?.cgImage)
}
}
而且您可以像这样使用它:
downloadImage { image in
guard let image = image else { return }
// use image here
}
// but not here
但是,让我们退后一步,看看整个模式。您说您想“保存”结果。如果您要谈论将其保存到持久性存储中,则根本不想使用CGImage
(UIImage
或任何其他方式)。这在计算上效率低下(将资产转换为图像,然后再转换回Data
以便可以保存),空间效率低下(必须将整个资产同时加载到内存中),并且可能会带来问题(例如,如果您下载JPG,转换到CGImage
,然后尝试重新建立一个JPG,将所得的资产会略有不同,更大,和/或与新JPG伪影)。如果您只是预下载资产,请使用简单的网络库(例如Alamofire或)URLSession
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句