fileManager.createFileAtPath always fails

前端 未结 2 647
-上瘾入骨i
-上瘾入骨i 2020-12-19 06:33

I try to call the fileManager.createFileAtPath-method, but it always fails. My variable success is always false. I looked at some simi

2条回答
  •  感动是毒
    2020-12-19 07:22

    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.

提交回复
热议问题