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.