ios - fileManager.createFileAtPath 总是失败

标签 ios swift nsfilemanager

我尝试调用 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 始终为 false。我希望你能帮我解决这个问题。 非常感谢任何帮助。谢谢

最佳答案

这里有个问题:

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)

关于ios - fileManager.createFileAtPath 总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069697/

相关文章:

iOS Meteor Cordova 应用程序 : all app graphics disappear after a few minutes

ios - XCODE swift - webview 无法打开 ics 链接 - 在 safari 中它有效

ios - UITableView 和 UINavigationBar 自定义混淆。关于如何完成的任何建议?

ios - NSFileManager,如何判断一个文件或目录是否可以删除?

ios - Swift 如何在临时文件夹中创建复杂的文件夹结构

iOS 自定义 View 不会立即显示图像

ios - 为什么无法触发textFieldShouldBeginEditing方法?

ios - 使用 UINavigationController 和 UINavigationBar 时图层的 y 位置动画错误

Swift 4 协议(protocol)扩展 - 便利初始化器默认实现

objective-c - NSFileSize 只返回 102