現在、SwiftでJSONをパースしてRealmに保存、そして画面遷移してからtextなどにRealmから取り出したJSONデータを表示するようにしたいのですが、JSONを辞書型にパース?するところで足踏みしています。
どなたかご教授お願いします。
ViewController
1 2import UIKit 3import RealmSwift 4 5class ViewController: UIViewController { 6 7 @IBOutlet weak var myTextView: UITextView! 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 12 let config: URLSessionConfiguration = URLSessionConfiguration.default 13 14 // Sessionを生成. 15 let session: URLSession = URLSession(configuration: config, delegate: self as? URLSessionDelegate, delegateQueue: nil) 16 17 // 通信先のURLを生成. 18 let url:URL = URL(string: "JSONデータがあるURL")! as URL 19 20 // タスクの生成. 21 let task: URLSessionDataTask = session.dataTask(with: url as URL, completionHandler: { (data, response, err) -> Void in 22 23 if data != nil { 24 25 let str = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) 26 print(str!) 27 DispatchQueue.main.async(execute: { 28 self.myTextView.text = "(str!)" 29 }) 30 31 do { 32// JSONパース。optionsは型推論可 33 let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) 34 35 // (".allowFragmets"等) 36 let top = json as! NSArray 37 38 // バックグラウンドだとUIの処理が出来ないので、メインスレッドでUIの処理を行わせる. 39 DispatchQueue.main.async(execute: { 40 41 }) 42 } catch { 43 print(error) 44 } 45 } 46 }) 47 // タスクの実行 48 task.resume() 49 } 50 override func didReceiveMemoryWarning() { 51 super.didReceiveMemoryWarning() 52 53 } 54} 55
このViewControllerにあるtextViewは確認をしたくて入れています。
下記がJSONの中身です。
JSON
1{ "DATA": [{ "version": "1.2.3", "bundleID": "asx.testApp" }], "DATA2": [{ "version": "9.9.9", "bundleID": "asx.mainApp" }] }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/26 12:07