ViewController1に配置したButtonからViewController2へ遷移し
TableViewCellへ値を渡したいのですが、Buttonのタップ時に
PHP経由でサーバーから受け取ったJSONデータをパースして
変数(jDataList)に格納後、格納したものをViewController2に渡したいです。
Buttonのタップイベントの中にデータ取得処理を記載し、
ButtonからViewControllere2へセグエを作成し下記の様に実装しましたが
データ取得よりも先に下記のprepareの方が先に処理されてしまい値を渡すことができません。
ソースで画面遷移するパターンなど色々試しましたが解決策がわかりません。
ViewControllerのIdentiferの設定やStoryBordでのセグエの設定が必要かもよくわからないため詳細に教えていただければ幸いです。
*画面遷移時の処理
SWIFT
1override func prepare(for segue: UIStoryboardSegue, sender: Any!) { 2 if segue.identifier == "toViewControllerSegue" { //ThirdViewControllerに遷移する場合 3 4 //View Controllerへ値を渡す 5 let VC = segue.destination as! ViewController2 6 VC.jDataList = self.json 7 print(json) 8 } 9 }
*データ取得処理
SWIFT
1 let urlStr = "http://192.168.xxx.xxx/testpage/jsontest.php" 2 let encodedURL = urlStr.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) 3 4 if let url = URL(string: encodedURL!) { 5 let req = NSMutableURLRequest(url: url) 6 req.httpMethod = "POST" 7 8 let task = URLSession.shared.dataTask(with: req as URLRequest, completionHandler: { (data, resp, err) in 9 print(resp!.url!) 10 print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as Any) 11 12 // 受け取ったdataをJSONパース、エラーならcatchへジャンプ 13 do { 14 // dataをJSONパースし、グローバル変数"getJson"に格納 15 self.json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 16 17 18 //ストーリーボードのインスタンスを作成 19 let storyboard: UIStoryboard = self.storyboard! 20 //検索結果画面のビューのインスタンスを作成 21 let nextView = storyboard.instantiateViewController(withIdentifier: "toViewController") as! ViewController 22 //画面遷移を実行 23 self.present(nextView, animated: true, completion: nil) 24 } catch { 25 print (error) 26 return 27 } 28 }) 29 task.resume() 30 31 }
回答1件
あなたの回答
tips
プレビュー