I have a file named Data.plist in my main bundle (at the root of the app directory), and I am trying to copy this file to user document directory for read and write operations, however, I got the following error when trying to copy the file:
CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
Error in copying Data.plist: Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported
Code:
let fileManager = FileManager.default
var docDirectory: String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docDir = paths.first
return docDir
}
var dataFilePath: String? {
guard let docPath = self.docDirectory else { return nil }
return docPath.appending("/Data.plist")
}
func copyFile() {
guard let path = dataFilePath else {
return
}
guard fileManager.fileExists(atPath: path) else {
// NSLog("Creating Data.plist")
// fileManager.createFile(atPath: path, contents: nil, attributes: nil) // create the file
// NSLog("created Data.plist file successfully")
if let bundlePath = Bundle.main.path(forResource: "Data", ofType: "plist") {
do {
let fromURL = URL(string: bundlePath)!
let toURL = URL(string: "file://\(path)")!
try fileManager.copyItem(at: fromURL, to: toURL)
NSLog("Copied Data.plist to Document directory")
} catch let error {
NSLog("Error in copying Data.plist: \(error)") // see the above quoted error message from here
}
}
return
}
}