簡體   English   中英

Swift:首次運行應用程序時,如何將文件從應用程序包復制到“文檔”文件夾

[英]Swift: How to copy files from app bundle to Documents folder when app runs for first time

關於SO的各種示例代碼和問題,涉及如何在應用程序首次運行時以編程方式將Obj-C中的文件從應用程序捆綁包復制到應用程序的沙盒Documents文件夾(例如hereherehere )。

您如何在Swift中做到這一點?

您可以使用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")

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM