首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fileManager.createFileAtPath总是失败

fileManager.createFileAtPath总是失败
EN

Stack Overflow用户
提问于 2016-01-28 18:55:30
回答 2查看 9.3K关注 0票数 13

我试图调用fileManager.createFileAtPath-method,但总是失败。我的变量success总是false。我看了一些类似的帖子,但没有完全符合我的需要。这是我的代码:

代码语言:javascript
复制
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)")
                }

,以下是我试图修复这个问题的方法:

我试着用这个方法

代码语言:javascript
复制
let success = NSFileManager.defaultManager().createFileAtPath(String(pListPath), contents: data, attributes: nil)

而且还

代码语言:javascript
复制
let success = data.writeToFile(String(pListPath), atomically: true)

但什么都不管用。success总是false。我还尝试给它一个文本字符串作为路径,将contents设置为nil,我甚至将目录权限更改为777,但注意到是有效的。success总是错误的。我希望你能帮上忙。任何帮助都是非常感谢的。谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-28 19:17:47

以下是一个问题:

代码语言:javascript
复制
if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)

不能使用String(...)NSURL转换为文件路径字符串,必须使用path方法:

代码语言:javascript
复制
if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)

如果reportsPath也是NSURL,那么在

代码语言:javascript
复制
pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

这应该是

代码语言:javascript
复制
let pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)
票数 19
EN

Stack Overflow用户

发布于 2016-01-28 18:59:26

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

代码语言:javascript
复制
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)
        }
    }
}

确保您正在相对地将文件写入用户域文件夹。

代码语言:javascript
复制
 // i.e. Caches, Documents...
 let rootPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) 

可能,您丢失了斜杠字符,或者您跳过了某些文件夹的创建。

如果您有. dir2 /dir2 2/ file.ext,则需要创建dir1,然后是dir2,最后是file.ext。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35069697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档