gpt4 book ai didi

ios - fileManager.createFileAtPath 总是失败

转载 作者:搜寻专家 更新时间:2023-10-31 21:53:23 25 4
gpt4 key购买 nike

我尝试调用 fileManager.createFileAtPath 方法,但总是失败。我的变量 success 始终为 false。我在这里查看了一些类似的帖子,但没有一个完全符合我的需要。这是我的代码:

pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

let data: NSData = NSData()
var isDir: ObjCBool = false

if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)
{
print("File already exists")
}
else
{

let success = fileManager.createFileAtPath(String(pListPath), contents: data, attributes: nil)

print("Was file created?: \(success)")
print("plistPath: \(pListPath)")
}

以下是我尝试解决此问题的方法:

我试过用这个方法

let success = NSFileManager.defaultManager().createFileAtPath(String(pListPath), contents: data, attributes: nil)

还有

let success = data.writeToFile(String(pListPath), atomically: true)

但没有任何效果。 success总是false。我还尝试给它一个文字字符串作为路径,将 contents 设置为 nil 我什至更改了我想要将其放入 777 的目录权限,但注意到作品。 success 始终为 false。我希望你能帮我解决这个问题。非常感谢任何帮助。谢谢

最佳答案

这里有个问题:

if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)

您不能使用 String(...)NSURL 转换为文件路径字符串,你必须使用 path 方法:

if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)

如果reportsPath也是一个NSURL那么同样的问题存在于

pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

应该是

let pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)

关于ios - fileManager.createFileAtPath 总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com