LoginSignup
65
69

More than 5 years have passed since last update.

Swiftでリソースにあるjsonファイルを読み込む

Posted at

はじめに

ビルドしたわけじゃないのでコンパイルできるかも分かりませんがSwiftでリソースにあるjsonファイルを読み込むためのメモを残しておきます

読み込む例

リソースとしてdummy.jsonというjsonのファイルがあるとする

dummy.json
{
  "hoge":"piyo"
}

これをSwiftで読み込む例

let path : String = NSBundle.mainBundle().pathForResource("dummy", ofType: "json")
let fileHandle : NSFileHandle = NSFileHandle(forReadingAtPath: path)
let data : NSData = fileHandle.readDataToEndOfFile()

if data {
    var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data,
                                            options: NSJSONReadingOptions.AllowFragments,
                                            error: nil) as NSDictionary

    if !jsonError {
       //jsonからhogeというデータを取得する例
       if let hoge = json.objectForKey("hoge") as? String {
           //hogeがあるということが保証されている
           self.hoge = hoge
       } else {
           //hogeない
       }
    } else {
       //jsonのパースエラー
    }

} else {
    //dataがnilだとNSInvalidArgumentExceptionで例外になるよ
}

例外処理について

Swiftは例外のcatchができないみたい。NSJSONSerialization.JSONObjectWithDataメソッドでnilを渡した際には例外となるのでnilチェックを行う必要がある。

65
69
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
65
69