I'm downloading some cover images for books from the web and save them to Library/Caches/temporary. This works great, I've verified it width Finder, that the path is correct and the name of file is correct.
I can't seem to read the image from disc, though the path is correct and the image is for sure there.
I'm getting the URL for Library/Caches fresh on each run. I'm appending a constant temporary each time I need that folder(where the cover images are saved)
Getting the Library/Cache path
self.cachesDirectory = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
Saving the image(AssetsHandler.sharedInstance)
func tempSaveCover(withDataAndISBN data: Data, isbn: String){
if let image = UIImage(data: data){
if let pngRepresentation = UIImagePNGRepresentation(image){
let path = self.cachesDirectory.appendingPathComponent(Constants.AssetsHandler.tempCoverPath, isDirectory: true).appendingPathComponent(isbn).appendingPathExtension("png")
do{
try pngRepresentation.write(to: path)
}catch let error{
print("Can't write png to disc: \(error.localizedDescription)")
}
}
}
}
This is how the URL looks like file:///Users/Joakim/Library/Developer/CoreSimulator/Devices/EBA74A27-B09C-4AFC-B825-ECDC37445053/data/Containers/Data/Application/A2B398CF-8535-492A-9787-D088C24ED661/Library/Caches/temporary/9788203196195.png
Reading the image(AssetsHandler.sharedInstance)
func tempGetCover(withISBNNumber isbn: String) -> UIImage{
let path = self.cachesDirectory.appendingPathComponent(Constants.AssetsHandler.tempCoverPath, isDirectory: true).appendingPathComponent(isbn).appendingPathExtension("png")
if let cover = FileManager.default.contents(atPath: path.absoluteString){
if let image = UIImage(data: cover) {
return image
}
}
/*if let image = UIImage(contentsOfFile: path.absoluteString){
return image
}*/
return UIImage(named: "default-image")!
}
Getting the image(Book class)
var coverImage: UIImage? {
get{
guard let idisbn = self.isbn else {return UIImage(named:"default-image")}
/*if let image = UIImage(contentsOfFile: AssetsHandler.sharedInstance.path(for: idisbn).absoluteString){
print("Image: ok")
return image
}*/
return AssetsHandler.sharedInstance.tempGetCover(withISBNNumber: idisbn)
//return UIImage(named:"default-image")
}
set(image){
self.coverImage = image
}
}
I have verified that the passing argument ISBN is the same. Also that the image are saved before I try to read it.
Any ideas why I'm only able to display the default-image ?