【问题标题】:How to copy a folder of files from IOS App bundle resources to Documents Directory如何将文件文件夹从 IOS App 捆绑资源复制到 Documents Directory
【发布时间】:2019-07-02 22:17:19
【问题描述】:

我想在应用程序启动时在 IOS 应用程序文档文件夹中预先填充 txt 文件的文件夹结构,复制我已作为资源添加到我的应用程序包中的预先准备好的文件文件夹。

如何浏览 IOS 应用程序包中的分层文件夹结构并请求每个子文件夹的内容,然后是每个文件的内容。

【问题讨论】:

    标签: ios file copy bundle nsdocumentdirectory


    【解决方案1】:

    要列出 App Bundle 中的项目,您可以使用以下代码:

    do {
        let fileURLs = try FileManager.default.contentsOfDirectory(at: Bundle.main.bundleURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        for url in fileURLs {
            print("fileURL = \(url)")
        }
    } catch let error {
        // Error Handle
    }
    

    将 App Bundle 中的“MyTextFiles”文件夹复制到您的 App 文档文件夹:

        do {
            guard let myTextFilesInBundleURL = Bundle.main.url(forResource: "MyTextFiles", withExtension: nil) else { return }
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let myTextFileURL = URL(fileURLWithPath: docPath).appendingPathComponent("MyTextFiles")
            try FileManager.default.copyItem(at: myTextFilesInBundleURL, to: myTextFileURL)
        } catch let error {
            // Error Handle
        }
    

    要在应用启动时执行此操作,您可以将此代码放入didFinishLaunchingWithOptionsapplicationDidBecomeActive

    希望这会有所帮助。

    【讨论】:

    • 谢谢。我会在星期一试试这个
    • 我希望有一些代码可以创建文件夹层次结构的精确副本,即具有子文件夹的文件夹,然后包含可能低至 4 个级别的子文件夹。但是你给了我一些想法,当我完成后我会在这里发布一个例子。
    猜你喜欢
    • 2012-04-07
    • 2019-08-06
    • 2018-05-23
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2010-11-11
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多