2

I would like to save images from my app to the Files app

enter image description here

in the following hierarchy:

Files
  MyAppFolder
    FolderA
      fileA1.png
      fileA2.png
      fileA3.png
    FolderB
      fileB1.png
      fileB2.png
      fileB3.png

I am trying to use the following code from here:

func saveImage(image: UIImage) -> Bool {
    guard let data = UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {   
        print(error.localizedDescription)
        return false
    }
}

But the file is no where to be found in the Files app.

I guess the url to the Files should be something else. But what?

Luda
  • 7,282
  • 12
  • 79
  • 139
  • You can't save files out of your app bundle. Only the user can do it – Leo Dabus Feb 15 '22 at 21:00
  • 1
    Not related to your question but your code is outdated `UIImagePNGRepresentation(image)` has been renamed to `image.pngData()` – Leo Dabus Feb 15 '22 at 21:03
  • I would also remove the guard from the let directory, change `try?` to `try` and move it inside your do try catch logic. This will allow you to do not force unwrap its value when writing it to disk. Btw don't cast to `NSURL` – Leo Dabus Feb 15 '22 at 21:05
  • Try this https://stackoverflow.com/questions/46456481/how-to-write-a-file-to-a-folder-located-at-apples-files-app-in-swift – BPS Feb 15 '22 at 21:22
  • If you would like to expose your app bundle files inside Files OnMyPhone you can check this post [How can I display my App documents in the Files app for iPhone](https://stackoverflow.com/a/70613710/2303865) – Leo Dabus Feb 15 '22 at 22:57

0 Answers0