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

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

我正在开发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")

    }
}

有什么建议吗?

swift uiimage nsurlconnection nsfilemanager nsdocumentdirectory
1个回答
0
投票

首先,您需要此扩展名,因为您将大量使用它

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))")
          }
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.