Swift 3:使用FileManager复制文件时出错

Ton*_*yGW 1 copy-item nsfilemanager ios swift3

我在我的主程序包(在app目录的根目录)中有一个名为Data.plist的文件,我正在尝试将此文件复制到用户文档目录以进行读写操作,但是,我在尝试时遇到以下错误复制文件:

CFURLCopyResourcePropertyForKey失败,因为它传递了一个没有方案的URL

复制Data.plist时出错:Error Domain = NSCocoaErrorDomain Code = 262"无法打开文件,因为不支持指定的URL类型

码:

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
        }

}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 9

必须使用fileURLWithPath初始化程序创建文件系统URL,该初始化程序会添加file://错误消息所抱怨的方案:

let fromURL = URL(fileURLWithPath: bundlePath)
let toURL = URL(fileURLWithPath: path)
Run Code Online (Sandbox Code Playgroud)

然而,有一种更方便的方法来创建fromURL:

if let fromURL = Bundle.main.url(forResource: "Data", withExtension: "plist") { ...
Run Code Online (Sandbox Code Playgroud)

例如,我建议通常使用与URL相关的API

var docDirectory: URL {
    return try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
}

var dataFileURL: URL {
    return docDirectory.appendingPathComponent("Data.plist")
}
Run Code Online (Sandbox Code Playgroud)

最大的好处是你获得了非可选值并且摆脱了几个guards.