###前提・実現したいこと
JSONデータをパースして得られたデータをTextViewに表示させたい。
###発生している問題・エラーメッセージ
ログにJSONの生データを出力することはできますが、パースはできません。
###ソースコード
swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 @IBOutlet weak var myText: UITextView! 6 7 override func viewDidLoad() { 8 super.viewDidLoad() 9 // Do any additional setup after loading the view, typically from a nib. 10 11 12 let urlStr = 13 if let url = NSURL(string: urlStr) { 14 let urlSession = NSURLSession.sharedSession() 15 let task = urlSession.dataTaskWithURL(url, completionHandler: self.onGetWeather) 16 task.resume() 17 } 18 } 19 20 func onGetWeather(data: NSData?, res: NSURLResponse?, error: NSError?) { 21 print(data) 22 23 do { 24 25 let jsonDic = try NSJSONSerialization.JSONObjectWithData( 26 data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary 27 28 guard let code = jsonDic["code"] as? Int else { 29 return 30 } 31 32 if code != 200 { 33 if let errorMessage = jsonDic["message"] as? String { 34 dispatch_async(dispatch_get_main_queue()){ 35 self.myText.text = errorMessage 36 } 37 } 38 } 39 40 guard let data = jsonDic["data"] as? NSDictionary else { 41 return 42 } 43 44 guard let weather = data["weather_times"] as? String else { 45 return 46 } 47 dispatch_async(dispatch_get_main_queue()){ 48 self.myText.text = String(weather) 49 } 50 } catch { 51 dispatch_async(dispatch_get_main_queue()){ 52 self.myText.text = "エラーです" 53 } 54 } 55 } 56 57 override func didReceiveMemoryWarning() { 58 super.didReceiveMemoryWarning() 59 // Dispose of any resources that can be recreated. 60 } 61 62}
###補足情報(言語/FW/ツール等のバージョンなど)
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/09 06:24