Swift:首次运行应用程序时,如何将文件从应用程序包复制到“文档”文件夹

时间:2019-01-02 21:04:09

标签: ios swift

关于SO的样例代码和问题种类繁多,涉及如何以编程方式将Obj-C中的文件从应用程序包复制到应用程序的沙盒文档文件夹(例如hereherehere)在应用程序首次运行时。

您如何在Swift中做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用FileManager API:

下面是带有复制具有指定扩展名的所有文件的函数的示例:

func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
        do {
            let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
            let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
            for fileName in filteredFiles {
                if let documentsURL = documentsURL {
                    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
                    let destURL = documentsURL.appendingPathComponent(fileName)
                    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
                }
            }
        } catch { }
    }
}

用法:

copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")

答案 1 :(得分:-1)

对于Swift 4.2:

假设您的应用程序捆绑包中的文件名为Some File.txt

ViewDidLoad中,添加:

let docName = "Some File"
let docExt = "txt"
copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)

,然后创建如下函数:

func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
    guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
        else {
            print("Source File not found.")
            return
    }
        let fileManager = FileManager.default
        do {
            try fileManager.copyItem(at: sourceURL, to: destURL)
        } catch {
            print("Unable to copy file")
        }
}