如何使用SDWebImage下载和保存CGImage

问题描述 投票:0回答:1

我正在尝试使用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!
}
swift sdwebimage
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.