【发布时间】:2020-12-04 23:52:11
【问题描述】:
我在每次启动应用程序时更改文件路径时遇到问题。 我在应用程序包中有一个文件(“AppConstant.json”),我需要将此文件复制到应用程序文档目录中。我已成功将“AppConstant.json”文件保存在 Document 目录上创建的用户文件夹“MyFolder”中。
但问题是当我第二次重新启动应用程序时,它没有显示相同的路径。我也在使用相对路径,但仍然没有得到。
这里是代码 // 调用目录
let stringAppConstant = copyFileFromBundleToDocumentDirectory(resourceFile: "AppConstant", resourceExtension: "json")
//保存或获取退出文件路径
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) -> String
{
var stringURLPath = "Error_URLPath"
let fileManager = FileManager.default
let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
if !fileManager.fileExists(atPath: newDestPath.path) {
do {
try fileManager.createDirectory(atPath: newDestPath.path,withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", newDestPath.path)
} catch {
print("Error in creating folder :::",error.localizedDescription);
}
}
else {
print("Folder is already exist!")
}
if fileManager.fileExists(atPath: fullDestPath.path) {
print("File is exist in ::: \(fullDestPath.path)")
stringURLPath = fullDestPath.path
}
else {
do {
try fileManager.copyItem(atPath: sourcePath, toPath: fullDestPath.path)
print("Saved file successfully in :::", fullDestPath.path)
stringURLPath = fullDestPath.path
} catch {
print("Error in creating file ::: \(error.localizedDescription)")
}
}
return stringURLPath
}
请帮助我,我需要在 Sandbox 中保存路径。这是我实施的正确方式吗?
我在设备和模拟器中运行,重新启动时两条路径不同 这是首次启动的路径: /var/mobile/Containers/Data/Application/81B568A7-0932-4C3E-91EB-9DD62416DFE8/Documents/MyFolder/AppConstant.json
重新启动我正在获取新路径的应用程序: /var/mobile/Containers/Data/Application/3DAABAC3-0DF5-415B-82A5-72B204311904/Documents/MyFolder/AppConstant.json
注意:我创建了一个示例项目,并使用了相同的代码并且它正在工作。但在现有项目中它不起作用。我仅对示例和项目使用相同的包 ID 和配置文件。检查文件添加参考,设置,版本都一样。
有什么想法吗?
【问题讨论】:
-
帮助缩小范围的问题 - 当您说“未显示相同的路径”时,您是指 fullDestPath 吗?另外,您是在模拟器中运行,还是在实际设备上运行?当您“再次启动”时,您是以相同的方式启动还是以不同的方式启动(例如从 Xcode 调试一次启动而不是另一次启动)?
-
嗨@Corbell,我更新了我的问题。我同时启动了设备和模拟器,它们的行为也相同。下次我启动相同的方式来调用该方法时
-
copyFileFromBundleToDocumentDirectory的返回值怎么办?如果您将其存储以稍后访问该文件,则可能会出现问题,因为它包含绝对路径而不是相对路径。 -
嗨@GlebA.,在启动应用程序时(第一次启动-第一次安装)我将文件保存在文档目录中,之后我需要使用相同的文件(已经保存在文档目录中的文件)以供进一步使用。那么我怎样才能得到“相对路径”。请指导我
-
我猜这个说法是错误的
let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)")可以换成let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: resourceExtension)
标签: ios swift file-manager