2

I'm tryin to write the datas of an Image in the cacheDirectory, like this :

let imageData = UIImageJPEGRepresentation(image, 1.0) else { fatalError("Impossible to read the image") }
try! imageData.write(to: cachedImageURL, options: .atomic)
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))

Where image is a working UIImage. the Print statement always returns False. The file is never written, and any exception is raised due to the "try!"

Any idea ?

printing the cachedImageURL, it looks like this

file:///var/mobile/Containers/Data/Application/7B6B72C8-E794-4474-A658-48B66AEA31EC/Library/Caches/79d0e60e-5961-4538-bd9f-28187f4e26d0.jpg

Leo
  • 23,601
  • 9
  • 64
  • 89
Alexis Darnat
  • 561
  • 6
  • 13

2 Answers2

1

Just figured out. The problem come from my print

print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))

which should be cachedImageURL.path insteadOf cachedImageURL.absoluteString

print(fileManager.fileExists(atPath: cachedImageURL.path))
Alexis Darnat
  • 561
  • 6
  • 13
0

You can Try below Code for saving Images to Caches Directory

*NOTE : if you are saving more than one, please give different image name for all

let fileManager = FileManager.default
let imageName = "image.jpg" //Need to change if more images want to save

do {
    let cachesDirectory = try fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
    let fileURL = cachesDirectory.appendingPathComponent(imageName)
    let image = your image //Give your image here
    if let imageData = UIImageJPEGRepresentation(image, 1.0) {
        try imageData.write(to: fileURL)
        print("Image Saved")
    }
} catch {
       print(error.localizedDescription)
}
LinusGeffarth
  • 21,607
  • 24
  • 100
  • 152
Rohit Makwana
  • 2,835
  • 12
  • 23