fileManager.createFileAtPath总是失败 [英] fileManager.createFileAtPath always fails
问题描述
我尝试调用fileManager.createFileAtPath
方法,但是它总是失败.
我的变量success
始终为false
.我在这里查看了一些类似的帖子,但没有一个完全适合我的需求.
这是我的代码:
I try to call the fileManager.createFileAtPath
-method, but it always fails.
My variable success
is always false
. I looked at some similar posts here but nothing fits my needs exactly.
Here is my code:
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
始终为假.希望您能为您提供帮助.
任何帮助,我们将不胜感激.谢谢
But nothing works. success
is always false
.
I also tried to give it a literal-String as a path, set contents
to nil
and I even changed the directory permissions where i want to put it to 777, but noting works. success
is always false. I hope you can me help out of this.
Any help is highly appreciate. Thank you
推荐答案
这是一个问题:
if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)
您不能使用String(...)
将NSURL
转换为文件路径字符串,
您必须使用path
方法:
You cannot use String(...)
to convert a NSURL
to a file path string,
you have to use the path
method:
if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)
如果reportsPath
也是NSURL
,则存在相同的问题
If reportsPath
is also an NSURL
then the same problem exists at
pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)
应该是
let pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)
这篇关于fileManager.createFileAtPath总是失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!