【问题标题】:How to read a playground text resource files with Swift 2 and Xcode 7如何使用 Swift 2 和 Xcode 7 读取 Playground 文本资源文件
【发布时间】:2015-06-20 18:27:51
【问题描述】:

Xcode 7 Playgrounds 现在支持从 nested Resources 目录加载文件。

当我的Resources 中有GameScene.sks 时,我可以获得SKScene(fileNamed: "GameScene"),如果我的Resources 中有GameScene.png,我可以得到NSImage(named:"GameScene.png")

但是我怎样才能从 Playground Resources 目录中读取常规文本文件呢?

【问题讨论】:

    标签: ios xcode swift-playground xcode7


    【解决方案1】:

    我们可以使用Bundle.main

    所以,如果你的操场上有一个 test.json,比如

    你可以像这样访问它并打印它的内容:

    // get the file path for the file "test.json" in the playground bundle
    let filePath = Bundle.main.path(forResource:"test", ofType: "json")
    
    // get the contentData
    let contentData = FileManager.default.contents(atPath: filePath!)
    
    // get the string
    let content = String(data:contentData!, encoding:String.Encoding.utf8)
    
    // print
    print("filepath: \(filePath!)")
    
    if let c = content {
        print("content: \n\(c)")
    }
    

    将打印

    filepath: /var/folders/dm/zg6yp6yj7f58khhtmt8ttfq00000gn/T/com.apple.dt.Xcode.pg/applications/Json-7800-6.app/Contents/Resources/test.json
    content: 
    {
        "name":"jc",
        "company": {
            "name": "Netscape",
            "city": "Mountain View"
        }
    }
    

    【讨论】:

    • 这里值得一提。要获得资源,最好的方法是在 WorkSpace 中创建游乐场。我会默认出现在正确的位置。
    【解决方案2】:

    Jeremy Chone's 答案,已针对 Swift 3、Xcode 8 更新:

    // get the file path for the file "test.json" in the playground bundle
    let filePath = Bundle.main.path(forResource: "test", ofType: "json")
    
    // get the contentData
    let contentData = FileManager.default.contents(atPath: filePath!)
    
    // get the string
    let content = String(data: contentData!, encoding: .utf8)
    
    
    // print
    print("filepath: \(filePath!)")
    
    if let c = content {
        print("content: \n\(c)")
    }
    

    【讨论】:

    • filePath 应该被安全使用。请检查 filePath 是否不为零,例如使用 let。 contentData 也应该这样做。应该编写代码以便它可以处理这些有问题的情况。
    【解决方案3】:

    您可以直接将字符串与 URL 一起使用。 Swift 3 中的示例:

    let url = Bundle.main.url(forResource: "test", withExtension: "json")!
    let text = String(contentsOf: url)
    

    【讨论】:

      【解决方案4】:

      斯威夫特 5

      可以通过 Playground 中的捆绑包访问您的 Resources 文件夹中的文件。

      import UIKit
      

      这里有两种获取 JSON 数据的方法。

      路径:

          guard let path = Bundle.main.path(forResource:"test", ofType: "json"),
          let data = FileManager.default.contents(atPath: path) else {
              fatalError("Can not get json data")
          }
      

      网址:

          guard let url = Bundle.main.url(forResource:"test", withExtension: "json") else {
                  fatalError("Can not get json file")
          }
          if let data = try? Data(contentsOf: url) {
              // do something with data
          }
      

      【讨论】:

        【解决方案5】:

        另一种捷径(Swift 3):

        let filePath = Bundle.main.path(forResource: "test", ofType: "json")
        let content: String = String(contentsOfFile: filePath!, encoding: .utf8)
        

        【讨论】:

          【解决方案6】:

          为 swift3.1 添加了尝试:

          let url = Bundle.main.url(forResource: "test", withExtension: "json")!
          // let text = String(contentsOf: url)
          do {
              let text = try String(contentsOf: url)
              print("text: \n\(text)")
          }
          catch _ {
              // Error handling
          }
          
          // --------------------------------------------------------------------
          let filePath2 = Bundle.main.path(forResource: "test", ofType: "json")
          do {
              let content2: String = try String(contentsOfFile: filePath2!, encoding: .utf8)
              print("content2: \n\(content2)")
          
          }
          catch _ {
              // Error handling
          }
          

          【讨论】:

          • 忽略 catch 块中的错误是非常糟糕的做法。您不应该使用_ 运算符:只要有catch,它就会在块中正确生成error 变量。
          猜你喜欢
          • 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
          相关资源
          最近更新 更多