xCode playground和将文件写入Documents

时间:2016-12-22 19:09:35

标签: xcode nsfilemanager swift-playground

我正在尝试通过XCode的操场测试一些sqlite数据库调用。我从我的Playground的Resources文件夹中的数据库开始,并尝试将其移动到Playgrounds Documents文件夹,但是会发生的是生成指向链接到Resources文件夹中的文件的符号链接,因此我无法写入该文件。但是,如果我找出Documents文件夹的位置,然后从终端手动复制文件,一切正常。

那么为什么文件管理器复制命令实际上创建了一个sym链接而不是复制?有没有办法真正实现这一目标?这似乎只是游乐场的一个问题。从资源到文档的复制在应用程序本身中运行良好。

在操场上测试一些代码......

let dirPaths =     NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)
let docsDir = dirPaths[0]
let destPath = (docsDir as NSString).appendingPathComponent("/data.sqlite")
print(destPath)

let fileMgr = FileManager.default


let srcPath = Bundle.main.path(forResource: "data", ofType:"sqlite")
// This copies the data.sqlite file from Resources to Documents
//    ** However in the playground, only a symlink is generated
do {
    try fileMgr.copyItem(atPath: srcPath!, toPath: destPath)
} catch let error {
    print("Error (during copy): \(error.localizedDescription)")
}

1 个答案:

答案 0 :(得分:1)

罗德,现在为时已晚,但我想出来了。

<强>上下文

  • 我在同一个工作区中为我的项目添加了一个游乐场
  • 为了让游乐场与我的项目一起工作,我创建了一个框架
  • 我将Store.db文件添加到框架目标
  • 我还没有将Store.db作为资源添加到Playground
  • Swift 3

<强>游乐场

@testable import MyAppAsFramework

func copyMockDBToDocumentsFolder(dbPath: String) {
    let localDBName = "Store.db"
    let documentPath = dbPath / localDBName
    let dbFile = Bundle(for: MyAppAsFrameworkSomeClass.self).path(forResource: localDBName.deletingPathExtension, ofType: localDBName.pathExtension)

    FileManager.copyFile(dbFile, toFolderPath: documentPath)
}

copyMockDBToDocumentsFolder(dbPath: "The documents path")

/ copyFile(x)等其他内容是运算符重载和扩展

extension String {

    public var pathExtension: String {
        get {
            return (self as NSString).pathExtension
        }
    }

    public var deletingPathExtension: String {
        get {
            return (self as NSString).deletingPathExtension
        }
    }

    public func appendingPath(_ path: String) -> String {
        let nsSt = self as NSString
        return nsSt.appendingPathComponent(path)
    }

}


infix operator / : MultiplicationPrecedence

public func / (left: String, right: String) -> String {
    return left.appendingPath(right)
}


extension FileManager { 

    class func copyFile(_ filePath: String?, toFolderPath: String?) -> Bool {

        guard let file = filePath else { return false }
        guard let toFolder = toFolderPath else { return false }

        var posibleError: NSError?

        do {
            try FileManager.default.copyItem(atPath: file, toPath:toFolder)
        } catch let error as NSError {
            posibleError = error
            print("CAN'T COPY \(error.localizedDescription)")
        }

        return posibleError == nil
    }

}