将所有包资源复制到 Documents 目录中的单独文件夹
Copy all the bundle resources to a separate folder inside the Documents directory
复制 Bundle 中包含的所有文件(不是 [NSBundle mainBundle]
)并将它们放入 [=] 中新创建的目录的正确方法是什么11=] 目录?
您需要一项一项地复制,这很简单。
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)
}
根据包的大小,这可能需要一些时间来执行,因此您可能希望在后台线程上执行此操作。
复制 Bundle 中包含的所有文件(不是 [NSBundle mainBundle]
)并将它们放入 [=] 中新创建的目录的正确方法是什么11=] 目录?
您需要一项一项地复制,这很简单。
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)
}
根据包的大小,这可能需要一些时间来执行,因此您可能希望在后台线程上执行此操作。