7

I have an issue with saving/replacing image files to the Documents folder in my app.

In the AppDelegate I have a two properties:

let documentsDirectory: URL = { return FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! }()
let defaultDirectory: URL = { return Bundle.main.bundleURL.appendingPathComponent("DefaultBlocks.bundle", isDirectory: true) }()

It looks like the path is valid, have a log output:

[Verbose] application(:didFinishLaunchingWithOptions:) > Docs URL: file:///var/mobile/Containers/Data/Application/6ED04DA7-077F-4AE2-AB74-2EED02932823/Documents/

[Verbose] application(:didFinishLaunchingWithOptions:) > Defaults URL: file:///var/containers/Bundle/Application/A11D6A4A-E108-483F-86EC-BBFA10E77F72/TheAwesomeApp.app/DefaultBlocks.bundle/

My app logic is: if user requested to reload default images, then replace images in the Documents folder with the reference copies from the app bundle.

I try to implement replacement in the code (called from didFinishLaunchingWithOptions):

func ReloadDefaults() {
    let fileManager = FileManager.default

    do {
        let destDirURL = appDelegate.documentsDirectory
        let defaultURLs = Bundle.main.urls(forResourcesWithExtension: "png", subdirectory: "DefaultBlocks.bundle/_default_images_")

        for url in defaultURLs! {
            let destURL: URL = destDirURL.appendingPathComponent(url.lastPathComponent)
            log.verbose("Src URL: \(url)")
            log.verbose("Dest URL: \(destURL)")
            _ = try fileManager.replaceItemAt(destURL, withItemAt: url.absoluteURL)
        }
    }
    catch {
        log.error("File copy error: \(error.localizedDescription)")
    }
}

[Verbose] ReloadDefaults() > Src URL: image-512.png -- file:///var/containers/Bundle/Application/A11D6A4A-E108-483F-86EC-BBFA10E77F72/TheAwesomeApp.app/DefaultBlocks.bundle/_default_images_/

[Verbose] ReloadDefaults() > Dest URL: file:///var/mobile/Containers/Data/Application/6ED04DA7-077F-4AE2-AB74-2EED02932823/Documents/image-512.png

Unfortunately I've got a error for the replaceItemAt call:

[Error] ReloadDefaults() > File copy error: You don’t have permission to save the file “image-512.png” in the folder “Documents”.

I have a recent versions of the Xcode and iOS.

  • Possible duplicate of [iOS9 Swift File Creating NSFileManager.createDirectoryAtPath with NSURL](https://stackoverflow.com/questions/32659869/ios9-swift-file-creating-nsfilemanager-createdirectoryatpath-with-nsurl) – paper1111 Jan 10 '18 at 09:20
  • 1
    May be, but all **replaceItemAt** declarations have an URL as a parameter and I can not pass just path without "file://" prefix. So I did not know how to fix this. – Alexey Malashin Jan 10 '18 at 10:18

0 Answers0