10

我的主包中有包含文件的文件夹,我想在首次启动应用程序时将它们复制/剪切到文档目录以从那里访问它们。我看过一些例子,但它们都在 Obj-C 中,而且我使用的是 Swift 3。我该怎么做?

4

1 回答 1

14

我设法使用 2 个功能来做到这一点:

func copyFolders() {
    let filemgr = FileManager.default
    filemgr.delegate = self
    let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
    let docsURL = dirPaths[0]

    let folderPath = Bundle.main.resourceURL!.appendingPathComponent("Test").path
    let docsFolder = docsURL.appendingPathComponent("Test").path
    copyFiles(pathFromBundle: folderPath, pathDestDocs: docsFolder)
}

func copyFiles(pathFromBundle : String, pathDestDocs: String) {
    let fileManagerIs = FileManager.default
    fileManagerIs.delegate = self

    do {
        let filelist = try fileManagerIs.contentsOfDirectory(atPath: pathFromBundle)
        try? fileManagerIs.copyItem(atPath: pathFromBundle, toPath: pathDestDocs)

        for filename in filelist {
            try? fileManagerIs.copyItem(atPath: "\(pathFromBundle)/\(filename)", toPath: "\(pathDestDocs)/\(filename)")
        }
    } catch {
        print("\nError\n")
    }
}
于 2017-06-15T13:58:55.120 回答