一尘不染

如何在快速的操场上读取文件

swift

我正在尝试使用以下内容使用Swift操场读取文本文件

let dirs : String[]? =    NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? String[]

if (dirs != nil) {
    let directories:String[] = dirs!;
    let dir = directories[0]; //documents directory
    let path = dir.stringByAppendingPathComponent(file);

    //read
    let content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
}

但是,这将失败且没有错误。似乎第一行阻止了Playground在下面输出任何内容


阅读 209

收藏
2020-07-07

共1个答案

一尘不染

这对我有用。我更改的唯一一件事是明确显示了文件名(在您的示例中已暗示)-也许您在“文件”变量的屏幕外定义中有错字?

let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]

let file = "trial.txt" // My change to your code - yours is presumably set off-screen
if let directories = dirs {
  let dir = directories[0]; //documents directory
  let path = dir.stringByAppendingPathComponent(file);

  //read
  let content = NSString(contentsOfFile: path, usedEncoding: nil, error: nil)
  // works...
}

更新Swift 4.2

正如@raistlin指出的那样,现在

let dirs = NSSearchPathForDirectoriesInDomains(
              FileManager.SearchPathDirectory.documentDirectory,
              FileManager.SearchPathDomainMask.userDomainMask,
              true)

或者,更简洁地说:

let dirs = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                .userDomainMask, true)
2020-07-07