Скопируйте все ресурсы пакета в отдельную папку в каталоге Documents - PullRequest
0 голосов
/ 15 марта 2019

Как правильно скопировать все файлы , содержащиеся в Пакете (не [NSBundle mainBundle]), и поместить их во вновь созданный каталог внутри каталога Documents?

1 Ответ

1 голос
/ 15 марта 2019

Вам нужно скопировать элементы по одному, это довольно просто.

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)
}

В зависимости от размера пакета это может занять некоторое время, поэтому вы можете выполнить это в фоновом потоке.

...