fileManager.createFileAtPath always fails

夙愿已清 提交于 2019-12-06 04:04:47

Here is a problem:

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

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)

If reportsPath is also an NSURL then the same problem exists at

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

which should be

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

Make sure that you try to create file in folder that already exists. First create folder, then you can create file at that path.

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)
        }
    }
}

Make sure you are writing file relatively to user domain folder.

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

Probably, you are missing the slash character, or you skip some folder creation first.

If you have ...dir1/dir2/file.ext than you need to create dir1, then dir2 and finally file.ext.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!