[英]How to copy a file from app bundle to the Documents folder with Cordova?
[英]Swift: How to copy files from app bundle to Documents folder when app runs for first time
您可以使用FileManager API:
這是帶有復制具有指定擴展名的所有文件的函數的示例:
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 { }
}
}
用法:
copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")
對於Swift 4.2:
假設您的應用程序捆綁包中的文件名為Some File.txt
在ViewDidLoad
,添加:
let docName = "Some File"
let docExt = "txt"
copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)
然后創建一個函數,如下所示:
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.