【问题标题】:fileManager.createFileAtPath always failsfileManager.createFileAtPath 总是失败
【发布时间】:2016-05-06 07:31:03
【问题描述】:

我尝试调用fileManager.createFileAtPath-方法,但总是失败。 我的变量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总是假的。我希望你能帮我解决这个问题。 任何帮助都非常感谢。谢谢

【问题讨论】:

标签: ios swift nsfilemanager


【解决方案1】:

这里有个问题:

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)

【讨论】:

    【解决方案2】:

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

    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) 
    

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

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

    【讨论】:

    • 谢谢你们。我只需要将创建行更改为:let success = fileManager.createFileAtPath(pListPath.path!, contents: data, attributes: nil) 现在它可以工作了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多