Ios 如何将文件夹从项目复制到文档目录
这是我的文件夹结构 我想将此标签文件夹复制到文档目录为此,我使用了以下代码Ios 如何将文件夹从项目复制到文档目录,ios,mobile,directory,swift4,document-directory,Ios,Mobile,Directory,Swift4,Document Directory,这是我的文件夹结构 我想将此标签文件夹复制到文档目录为此,我使用了以下代码 let fileManager = FileManager.default let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask) guard documentsUrl.count != 0 else {
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return // Could not find documents URL
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("Stickers")
if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("Stickers")
do {
try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
但这行不通。我得到一个错误,因为
注意:如果无法复制文件夹,则我希望将资产.xcsets复制到文档目录。我怎样才能做到这一点呢?请在下面输入代码。。
我用两个函数更新代码,将所有文件从文件夹复制到文档目录
希望它能起作用
func copyFolders() {
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return // Could not find documents URL
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("Stickers")
if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("Stickers")
do {
if !FileManager.default.fileExists(atPath:(finalDatabaseURL?.path)!)
{
try FileManager.default.createDirectory(atPath: (finalDatabaseURL.path), withIntermediateDirectories: false, attributes: nil)
}
copyFiles(pathFromBundle: (documentsURL?.path)!, pathDestDocs: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
}
func copyFiles(pathFromBundle : String, pathDestDocs: String) {
let fileManagerIs = FileManager.default
do {
let filelist = try fileManagerIs.contentsOfDirectory(atPath: pathFromBundle)
try? fileManagerIs.copyItem(atPath: pathFromBundle, toPath: pathDestDocs)
for filename in filelist {
try? fileManagerIs.copyItem(atPath: "\(pathFromBundle)/\(filename)", toPath: "\(pathDestDocs)/\(filename)")
}
} catch {
print("\nError\n")
}
}
嘿,我的文件夹被复制到文档文件夹中,但我也需要文件夹中的数据。请帮助此代码在文档目录中创建文件夹,但它没有复制此文件夹中的标签。您应该从该文件夹中选择一个文件。不要复制文件夹,在目录端必须给出一个文件名,我会更新一个代码…检查并使用它。只需调用-->copyFolders(),很抱歉在-->if中检查了捆绑路径!FileManager.default.fileExists(atPath:(finalDatabaseURL?.path)!)。我更新了…现在试试。希望它能起作用