将所有捆绑软件资源复制到Documents目录内的单独文件夹中

时间:2019-03-15 12:12:37

标签: ios objective-c nsfilemanager nsbundle nsdocumentdirectory

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

1 个答案:

答案 0 :(得分: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)
}

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