我应该在iOS中保存本地JSON文件?

时间:2015-08-03 21:16:29

标签: ios json swift

我是JSON文件的新手,正在研究它们。我应该把文件放在我的iOS / Xcode项目中以及我应该用什么代码来访问它?

1 个答案:

答案 0 :(得分:7)

我已将我的网站放入一个名为Resources的文件夹中:

enter image description here

但是,只要对您,您的团队或将继续从事该项目的开发人员有意义,您就可以放在任何您想要的地方。

我在我的AppDelegate中访问它,如下所示:

public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    let mainBundle = NSBundle.mainBundle()
    let fileName: String = "all"
    if let jsonPath = mainBundle.pathForResource(fileName, ofType: ".json", inDirectory: nil, forLocalization: nil), jsonData = NSData(contentsOfFile: jsonPath)
    {
        if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil), data = json.valueForKey("data") as? [AnyObject]
        {
            // do whatever you want with your JSON file
        }
    }

    return true
}

斯威夫特3:

if let jsonPath: String = Bundle.main.path(forResource: "all", ofType: "json"), let jsonData: Data = NSData(contentsOfFile: jsonPath) as? Data {
  do {
      let json: AnyObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as AnyObject
      if let data: Array<AnyObject> = json.value(forKeyPath: "data") as? Array<AnyObject> {
          // do whatever you want with the content of your json file
      }        
  } catch {
      print("Error while deserialization of jsonData")
  }
}