ios Swift 3 -将文件夹w/内容从主捆绑包复制到文档目录

goucqfw6  于 11个月前  发布在  iOS
关注(0)|答案(2)|浏览(112)

我的主包中有文件夹,我想在首次启动应用程序时将它们复制/剪切到文档目录中,以便从那里访问它们。我见过示例,但它们都是Obj-C,我使用的是Swift 3。我如何做到这一点?

dbf7pr2w

dbf7pr2w1#

我使用了两个函数:

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")
    }
}

字符串

xnifntxz

xnifntxz2#

有一个内置的文件管理器功能来做到这一点。
如果srcURL处的项目是目录,则此方法将复制该目录及其所有内容,包括任何隐藏文件。

do {
   let docsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
   let sourceURL = Bundle.main.resourceURL!.appendingPathComponent("sourceDir").absoluteURL
   let destinationURL = docsURL.appendingPathComponent("destDir").absoluteURL
               
   try FileManager.default.copyItem(at: sourceURL, to: destinationURL)     
} catch {
   print("\nError\n")
}

字符串

相关问题