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?
First, you want this extension because you will use it a ton
If you have the image URL you can get the image like this