我试图调用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。我还尝试给它一个文本字符串作为路径,将contents设置为nil,我甚至将目录权限更改为777,但注意到是有效的。success总是错误的。我希望你能帮上忙。任何帮助都是非常感谢的。谢谢
发布于 2016-01-28 19:17:47
以下是一个问题:
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)发布于 2016-01-28 18:59:26
确保您尝试在已经存在的文件夹中创建文件。首先创建文件夹,然后在该路径上创建文件。
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)
}
}
}确保您正在相对地将文件写入用户域文件夹。
// i.e. Caches, Documents...
let rootPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) 可能,您丢失了斜杠字符,或者您跳过了某些文件夹的创建。
如果您有. dir2 /dir2 2/ file.ext,则需要创建dir1,然后是dir2,最后是file.ext。
https://stackoverflow.com/questions/35069697
复制相似问题