gpt4 book ai didi

swift - 将 URL 数组转换为 UIImage 数组

转载 作者:搜寻专家 更新时间:2023-10-31 22:26:36 42 4
gpt4 key购买 nike

我有一组链接到图像文件的 URL,如何将它们存储到一组 UIImage 中?

var imagesArray = [UIImage]()

let links = ["http://example.com/image1.jpg","http://example.com/image2.jpg"] as [String]

必须有一个简单的解决方案。如果是一张图片,我可以执行以下操作:

let url = URL(string: link2image!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.image.append(image)

最佳答案

最简单的解决方案是遍历数组并使用 Data(contentsOf:) 同步下载图像,但是,由于同步执行,这将是非常不够的。

let images = links.flatMap{ link->UIImage? in
guard let url = URL(string: link) else {return nil}
guard let imageData = try? Data(contentsOf: url) else {return nil}
return UIImage(data: imageData)
}

更好的解决方案是并行异步下载图像,我为此使用 PromiseKit 编写了一个 UIImage 扩展。 :

extension UIImage {
class func downloadedAsync(fromUrl url: URL)->Promise<UIImage> {
return Promise{ fulfill, reject in
URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
guard let data = data, error == nil else {
reject(error!); return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
reject(NSError(domain: "Wrong HTTP response code when downloading image asynchronously",code: (response as? HTTPURLResponse)?.statusCode ?? 1000));return
}
guard let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let image = UIImage(data: data) else {
reject(NSError(domain: "No image in response", code: 700)); return
}
fulfill(image)
}).resume()
}
}
}

你称它为这样的链接数组:

var imageDownloadTasks = links.flatMap{ link in
guard let url = URL(string: link) else {return nil}
return UIImage.downloadedAsync(fromUrl: url)
}

然后执行 promise :

when(fulfilled: imageDownloadTasks).then{ images in
//use the images, images is of type [UIImage]
}

关于swift - 将 URL 数组转换为 UIImage 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692654/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com