【问题标题】:Copy all the bundle resources to a separate folder inside the Documents directory将所有捆绑资源复制到 Documents 目录中的单独文件夹
【发布时间】:2019-08-06 12:27:49
【问题描述】:

复制 Bundle(不是[NSBundle mainBundle])中包含的所有文件并将它们放到Documents 目录内新创建的目录中的正确方法是什么?

【问题讨论】:

  • 你所说的“捆绑包”是什么意思?任何Bundle 对象?
  • 使用 CocoaPods 创建的包。它可以是任何捆绑包。
  • 我刚刚添加了一个关于如何在运行时执行此操作的答案,但我猜您想将捆绑资源复制为构建阶段、预编译,对吧?
  • 不,在运行时。

标签: ios objective-c nsfilemanager nsbundle nsdocumentdirectory


【解决方案1】:

你需要一个一个地复制项目,这很简单。

let bundle: Bundle = ... // Whatever bundle you want to copy from
    guard let resourceURL = bundle.resourceURL else { return }
let fileManager = FileManager.default
do {
    let documentsDirectory = try fileManager.url(for: .documentDirectory,
                                                 in: .userDomainMask,
                                                 appropriateFor: nil,
                                                 create: false)
    let destination = documentsDirectory.appendingPathComponent("BundleResourcesCopy", isDirectory: true)

    var isDirectory: ObjCBool = false
    if fileManager.fileExists(atPath: destination.path, isDirectory: &isDirectory) {
        assert(isDirectory.boolValue)
    } else {
        try fileManager.createDirectory(at: destination, withIntermediateDirectories: false)
    }

    let resources = try fileManager.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)
    for resource in resources {
        print("Copy \(resource) to \(destination.appendingPathComponent(resource.lastPathComponent))")
        try fileManager.copyItem(at: resource,
                                 to: destination.appendingPathComponent(resource.lastPathComponent))
    }
} catch {
    print(error)
}

根据包的大小,这可能需要一些时间来执行,因此您可能希望在后台线程上执行此操作。

【讨论】:

  • 谢谢,所以我必须一个接一个地复制所有文件和文件夹。我需要 Objective-C 解决方案,但我可以以你为起点,用 Objective-C 重写。
猜你喜欢
  • 2019-07-02
  • 2012-04-07
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 2019-02-08
  • 1970-01-01
相关资源
最近更新 更多