今回は前回に引き続きSwiftyJSONの話です。
前回はXAMPPを用いてローカルサーバーを立ち上げてSwiftyJSONでローカルサーバーにあるJSONファイルを変換してって感じでした。
前回の記事
shinta1209.hatenablog.com
今回は実際にネットに転がっているJSONファイルを取得して表示させましょう。
① まず前回同様 SwiftyJSONをインストールします
② 全体のコード
まず全体のコードはこんな感じです。
次から一つずつ見て行きます。
(そして今回取得するJSONはこちら →) http://zipcloud.ibsnet.co.jp/api/search?zipcode=7830068
import UIKit
import SwiftyJSON
class ViewController: UIViewController {
let stringUrl = "http://zipcloud.ibsnet.co.jp/api/search?zipcode=7830068"
@IBAction func startParth(_ sender: Any) {
let url = URL(string: stringUrl)
let request = URLRequest(url: url!)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
let task:URLSessionDataTask = session.dataTask(with: request, completionHandler: { data, responce, error in
if error != nil {
print(error)
return
}
//メインスレッドで処理
DispatchQueue.main.async {
let json = JSON(data!)
print("JSONの中身をまず全て表示")
print("\(json)\nJSONの中身はここまで\n")
print("resultのkana1の中身を参照")
print("\(json["results"][0]["kana1"])\nkana1の中身だよん\n")
print("zipcode取得")
print("\(json["results"][0]["zipcode"])\nzipcodeだよん")
}
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
}
③ SwiftyJSONのimport
import SwiftyJSON
これをせずにはSwiftyJSONは使えませんから、忘れずにimportしましょう。
④ ターゲットのURLを格納
let stringUrl = "http://zipcloud.ibsnet.co.jp/api/search?zipcode=7830068"
⑤ ターゲットURLをURL型、URLRequest型に変換
let url = URL(string: stringUrl)
let request = URLRequest(url: url!)
⑥ HTTPセッションを作成
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
⑦ HTTP通信を実行する
let task:URLSessionDataTask = session.dataTask(with: request, completionHandler: { data, responce, error in
//errorがあれば吐き出す
if error != nil {
print(error)
return
}
//メインスレッドで実行
DispatchQueue.main.async {
//jsonにJSON型のdataを代入する
let json = JSON(data!)
print("JSONの中身をまず全て表示")
print("\(json)\nJSONの中身はここまで\n")
print("resultのkana1の中身を参照")
print("\(json["results"][0]["kana1"])\nkana1の中身だよん\n")
print("zipcode取得")
print("\(json["results"][0]["zipcode"])\nzipcodeだよん")
}
})
task.resume()
}
こんな感じです。
基本的には
→ URLを型変換して→ HTTPセッションを作成して → JSON解析開始
みたいな感じです。
自分もまだSwiftyJSONを触ったばかりなので、こんな書き方がいいよーとかがあれば是非コメントをください。
次はSwiftyJSON & Alamofireを使って解析して見ようと思います。