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

Swift 3: Error in copying file with FileManager

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

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

代码:

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
        }

}

文件系统 URLs 必须使用 fileURLWithPath 初始值设定项创建,它添加了错误消息抱怨的 file:// 方案:

let fromURL = URL(fileURLWithPath: bundlePath)
let toURL = URL(fileURLWithPath: path)

不过还有更方便的方法来创建fromURL:

if let fromURL = Bundle.main.url(forResource: "Data", withExtension: "plist") { ...

我建议一般使用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")
}

最大的好处是您可以获得非可选值并摆脱几个 guards。

检查文件 Data.plist 是否存在于 XCODE 项目中。