-1

I have a image cached in my apps document folder. I want to copy it in document folder. Till now i know that i can load my image as UIImage and then convert it to data and save it in my destination path. But is there any better approach than this? Like i don't want to convert my image in UIImage and again convert it to data and write.

My code for png is:

// Here sourcePath is original image path for example file//Document/dummy.png
// destinationPath is the path where i want to save my image for example file//Document/Image/anything.png
     if let img = UIImage(contentsOfFile: sourcePath), let data = img.pngData() {
        do {
              try data.write(to: destinationPath)
          } catch {
                
         }
       }

1 Answers1

1

FileManager provides an API to do that

try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)

or – preferable – the URL related counterpart

try FileManager.default.copyItem(at: sourceURL, to: destinationURL)

A path is just a simple String, with an URL you have instant access to a lot of attributes and metadata. Further URL provides all APIs to manipulate URLs for example changing the path extension or adding path components, for remote URLs even you can reliably manage components like scheme, host, query and fragment.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    I've always used the URL version, as it's the accepted best practice, but never bothered to think why! Do you happen to know, and can fit it into comment-sized reply ? :-) – flanker Mar 25 '21 at 12:30
  • Thank you i know that i can copy files but was not understanding why it was not working for image. Just now i noticed that i gave wrong destination path. Thanks btw. – Arnab Ahamed Siam Mar 25 '21 at 12:42
  • thanks @vadian. Kind of obvious if I *had* thought about it! – flanker Mar 25 '21 at 13:53
  • 1
    @ArnabAhamedSiam just to make it complete if you need to rename a file you can use `moveItem` and choose a different name at the destination url – Leo Dabus Mar 25 '21 at 16:27