如何将多个图像存储到文档目录并在 Swift 中获取路径



我正在研究 Swift 应用程序。

我收到如下服务器响应

[[“image_url": https://someurl1, "title": Title1], ["image_url": https://someurl2, "title": Title2], ["image_url": https://someurl3, "title": Title3], ["image_url": https://someurl4, "title": Title4]]

我必须将这些数据存储到数据库(Coredata(中。 但是在这些数据进入数据库之前,我必须下载图像,并且必须将它们添加到文档目录中,并且必须获取该路径。 如果用户离线,我必须将该文档路径存储到数据库中,我必须获取该路径并需要在 Tableview 上显示图像。

用于下载我在下面使用

func apiCall() {
// after api calls, getting response
for eachData in json {
print("eachData (eachData)")
let imageURL = eachData["image_url"]
if let url = imageURL {
let fileUrl = URL(string: url as! String)
print("fileUrl (fileUrl!)")
Home().downloadImage(from: fileUrl! )
//here I have to store each data into database after getting each image document path
}
}
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL) {
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
}
}

有什么建议吗?

首先,你想要这个扩展,因为你会经常使用它

extension FileManager {
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}

如果您有图像URL,则可以像这样获取图像

func fetchImageFrom(url: String) {
// This will make sure you're not saving a filename with slashes as
// they will be treated like directories
let urlArray = url.components(separatedBy: "/")
let fileName = urlArray.last!
DispatchQueue.global(qos: .userInitiated).async {
if let imageURL = URL(string: url) {
if let imageData = try? Data(contentsOf: imageURL) {
if let image = UIImage(data: imageData) {
// Now lets store it
self.storeImageWith(fileName: fileName, image: image)
}
}
}
}
}
func storeImageWith(fileName: String, image: UIImage) {
if let data = image.jpegData(compressionQuality: 0.5) {
// Using our extension here
let documentsURL = FileManager.getDocumentsDirectory()
let fileURL = documentsURL.appendingPathComponent(fileName)
do {
try data.write(to: fileURL, options: .atomic)
print("Storing image")
}
catch {
print("Unable to Write Data to Disk ((error.localizedDescription))")
}
}
}

最新更新