【问题标题】:Swift. Can`t save file to DocumentDirectory. Whats wrong?迅速。无法将文件保存到 DocumentDirectory。怎么了?
【发布时间】:2016-04-24 20:30:56
【问题描述】:

这是我的代码:

let fileName = "someFileName"

func saveDataToFile(urlStr:String){
    let url = NSURL(string: urlStr)
    var data:NSData!
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let directory = paths[0]
    let filePath = directory.stringByAppendingPathComponent(self.fileName)
    print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName

    let fileManager = NSFileManager.defaultManager()

    data = NSData(contentsOfURL: url!)
    print(data) // prints a lot of data     
    if data != nil{
        fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
    }

}

现在我想读取这些数据:

func readDataFromFile(){
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let directory = paths[0]
    let filePath = directory.stringByAppendingPathComponent(self.fileName)
    print(filePath) // prints the same path
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath){
            data = fileManager.contentsAtPath(filePath)
        }else{
            print("*****BAD*****") // always prints this which means that file wasn`t created
        }
}

第一个函数有什么问题?将文件保存到 DocumentDirectory 的正确方法是什么?

【问题讨论】:

  • .createFileAtPath 返回一个布尔值,表示操作是否成功完成,您应该检查一下。
  • 我现在检查并返回false,这并不奇怪。请问还有什么其他建议吗?
  • 好吧,既然我们知道第二个 sn-p 不是罪魁祸首,我们可以专注于第一个。只是看着它,我的猜测是filePath 是不正确的。但这只是我的猜测,必须调试更多。
  • 非常感谢,我会继续搜索

标签: swift2 nsfilemanager nsdocumentdirectory


【解决方案1】:

好的,在这种情况下,答案如下:

首先需要创建目录(又名文件夹),然后才在该目录中创建文件。

添加到代码中:

let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)

do{
    try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
    print(error.localizedDescription)
}

正如我在此之后所说的,你创建了你的文件:

fileManager.createFileAtPath(filePath, contents: data, attributes: nil)

感谢Eric.D

希望有人会觉得这很有用。

【讨论】:

  • ooc 你是如何创建fileManager 的?哦,nmd,您在问题中有该代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 2021-06-09
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多