小编典典

fileManager.createFileAtPath总是失败

swift

我尝试调用fileManager.createFileAtPath-method,但是它总是失败。我的变量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。我还尝试给它一个文字字符串作为路径,设置contentsnil,甚至更改了我想将其设置为777的目录权限,但注意了。success永远是错误的。希望您能为您提供帮助。任何帮助都非常感谢。谢谢


阅读 1089

收藏
2020-07-07

共1个答案

小编典典

这是一个问题:

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

您不能使用String(...)将a转换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)
2020-07-07