我正在使用iPad
在Xcode(version 8.2.1)
(v10.2.1)上制作游戏,而当我尝试将一些数据保存在沙箱中的文档文件夹中时,我发现我试过的所有方法都失败了:createDirectory
和createFile(using file manager)
,以及writeToUrl(使用NSData
)。我在2台iPad和1台iPhone上运行该程序,但没有成功。
我能够从我创建的plist中读取,并使用函数convertDataFrom()
将其转换为字典。
我对数据持久性或文件操作很陌生,我的游戏停留在这里。非常感谢任何帮助!
func loadData()->NSDictionary{
let fm = FileManager()
let sourceUrl = Bundle.main.url(forResource: "Data", withExtension: "plist")!
var appSupportDir = fm.urls(for: .documentDirectory, in: .userDomainMask).first! as? NSURL
appSupportDir = appSupportDir!.appendingPathComponent("UserData", isDirectory: true) as NSURL?
let urlForSave = (appSupportDir!.appendingPathComponent("Data.plist"))!
//load data, or if file doesn't exist yet, create one
var isDirectory: ObjCBool = false
if fm.fileExists(atPath: urlForSave.absoluteString, isDirectory: &isDirectory) {
let data = convertDataFrom(url: urlForSave)
print("data file exists")
print(isDirectory)
return data as NSDictionary
} else {
do { try fm.createDirectory(atPath: appSupportDir!.absoluteString!, withIntermediateDirectories: true, attributes: nil) }catch let Error {
print("create directory failed")
print(Error)
}
let originalData = NSData.init(contentsOf: sourceUrl)
print("\(urlForSave)")
do { try originalData?.write(toFile: urlForSave.absoluteString, options: .atomic) } catch let Error {
print(Error)
}
if (!fm.createFile(atPath: urlForSave.absoluteString, contents: originalData as Data?, attributes: nil)) {
fatalError("file creation failed")
}
let data = convertDataFrom(url: urlForSave)
print("\(data)")
print(isDirectory)
return data as NSDictionary
}
}
func convertDataFrom(url: URL)->Dictionary<String, Any> {
let dictionary = NSDictionary.init(contentsOf: url) as! Dictionary<String, Any>
return dictionary
}
&#34; createDirectory&#34;的错误消息:错误域= NSCocoaErrorDomain Code = 513&#34;您无权将文件“UserData”保存在 文件夹“Documents”。&#34; 的UserInfo = {NSFilePath =文件:/// VAR /移动/容器/数据/应用/ F7F41E0D-D3F6-489B-A59E-B7AC401EC402 /文档/的UserData /, NSUnderlyingError = 0x174053f50 {错误域= NSPOSIXErrorDomain代码= 1 &#34;不允许操作&#34;}} 文件:///var/mobile/Containers/Data/Application/F7F41E0D-D3F6-489B-A59E-B7AC401EC402/Documents/UserData/Data.plist
和&#34; createFile&#34; (如果createFile失败,则为fatalError)错误 Domain = NSCocoaErrorDomain Code = 4&#34;文件“Data.plist”没有 存在&#34。 的UserInfo = {NSFilePath =文件:///var/mobile/Containers/Data/Application/F7F41E0D-D3F6-489B-A59E-B7AC401EC402/Documents/UserData/Data.plist, NSUnderlyingError = 0x174055bd0 {错误域= NSPOSIXErrorDomain代码= 2 &#34;没有这样的文件或目录&#34;}}致命错误:文件创建失败:文件 /用户/ chanwu /桌面/ Math_DownStairs / Math_DownStairs /
答案 0 :(得分:1)
您的代码会检查urlForSave
(最终文件)是否存在,如果不存在,则尝试创建UserData目录。
如果最终文件不存在,但UserData目录不存在,我会期待您描述的确切结果。
您应该更改测试以查看UserData目录是否存在,而不是测试最终文件。这样,如果目录不存在,你将创建它,然后调用write(toFile:)
,如果文件不存在,将创建该文件。