为什么不在swift 3中将database.db从bundle复制到document目录?

时间:2016-09-28 09:30:47

标签: ios database swift copy

我尝试将我的数据库从包路径复制到目标路径(文档目录),并在 iOS8 Swift3 Xcode8 final :

    let bundlePath = Bundle.main.path(forResource: "cry", ofType: ".db")
    print(bundlePath, "\n") //prints the correct path
    let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let fileManager = FileManager.default
    let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("cry.db")
    let fullDestPathString = String(describing: fullDestPath)
    if fileManager.fileExists(atPath: fullDestPathString){
        print("Database file is exist")
        print(fileManager.fileExists(atPath: bundlePath!))
    }else{
        do{
            try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPathString)
        }catch{
            print("\n")
            print(error)
        }
    }  

但请告诉我错误

{Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}  

我检查了 atPath toPath 这是对的,但我不知道......
请帮帮我 谢谢

1 个答案:

答案 0 :(得分:7)

解决了

    let bundlePath = Bundle.main.path(forResource: "cry", ofType: ".db")
    let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let fileManager = FileManager.default
    let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("cry.db")
    if fileManager.fileExists(atPath: fullDestPath.path){
        print("Database file is exist")
        print(fileManager.fileExists(atPath: bundlePath!))
    }else{
        do{
            try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPath.path)
        }catch{
            print("\n",error)
        }
    }  

我将 .path 添加到我的目标地址,现在可以使用了。