[英]Swift: How to copy files from app bundle to Documents folder when app runs for first time
There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (eg here , here , and here ) when the application runs for the first time. 关于SO的各种示例代码和问题,涉及如何在应用程序首次运行时以编程方式将Obj-C中的文件从应用程序捆绑包复制到应用程序的沙盒Documents文件夹(例如here , here和here )。
How do you do this in Swift? 您如何在Swift中做到这一点?
You could use FileManager API: 您可以使用FileManager API:
Here's example with a function that copies all files with specified extension: 这是带有复制具有指定扩展名的所有文件的函数的示例:
func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
if let resPath = Bundle.main.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
for fileName in filteredFiles {
if let documentsURL = documentsURL {
let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
let destURL = documentsURL.appendingPathComponent(fileName)
do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
}
}
} catch { }
}
}
Usage: 用法:
copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")
For Swift 4.2: 对于Swift 4.2:
Assuming the file in your App Bundle is called Some File.txt
假设您的应用程序捆绑包中的文件名为Some File.txt
In ViewDidLoad
, add: 在ViewDidLoad
,添加:
let docName = "Some File"
let docExt = "txt"
copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)
and then create a function as follows: 然后创建一个函数,如下所示:
func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
else {
print("Source File not found.")
return
}
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
print("Unable to copy file")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.