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

时间:2017-03-13 18:11:07

标签: ios swift3 nsfilemanager copy-item

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

  

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

     

复制Data.plist时出错:错误域= NSCocoaErrorDomain代码= 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
        }

}

2 个答案:

答案 0 :(得分:7)

必须使用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")
}

最大的好处是获得非可选值并消除几个guard s。

答案 1 :(得分:0)

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