fileManager.createFileAtPath始终失败

我尝试调用fileManager.createFileAtPath -method,但它总是失败。 我变量的success总是false 。 我在这里查看了一些类似的post,但完全不符合我的需求。 这是我的代码:

 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总是错误的。 我希望你能帮我解决这个问题。 任何帮助都非常感谢。 谢谢

这是一个问题:

 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) 

确保您尝试在已存在的文件夹中创建文件。 首先创建文件夹,然后您可以在该路径创建文件。

 private class func assureDirPathExists(path: String) { if !NSFileManager.defaultManager().fileExistsAtPath(path) { do { try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription) } } } 

确保您正在相对于用户域文件夹写入文件。

  // ie Caches, Documents... let rootPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) 

您可能缺少斜杠字符,或者您首先跳过某些文件夹创建。

如果你有… dir1 / dir2 / file.ext,你需要创建dir1,然后是dir2,最后是file.ext。