How to store multiple images to document directory and fetch the path in Swift

904 Views Asked by At

I am working on Swift application.

I am getting server response like below

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

I have to store this data into database (Coredata). but before this data goes to database, I have to download images and I have to add them to document directory and I have to get that path . And that document path I have to store into database if user is offline, I have to fetch that path and needs to show images on Tableview.

for downloading I am using below

     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")

    }
}

Any suggestions?

1

There are 1 best solutions below

0
Waylan Sands On

First, you want this extension because you will use it a ton

extension FileManager {

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

If you have the image URL you can get the image like this

    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))")
          }
      }
}