現在、swiftでphpファイルから送られてきたjsonデータをパースして、
tableviewに表示するプログラムの作成を試みております。
jsonデータをパースするところまでは何とかたどり着いたのですが、
それをtableviewに反映させるやり方が分かりかねております。
今は// Cellで表示する配列以下の名前のリストがテーブルビューに
表示されておりますが、実現したいこととしては、
パースしたjsonデータがテーブルビューに
表示されるようにしたいと考えております。
大変不勉強な中でのご質問となり恐縮でございますが、
本来ならここで変数を設定しないと駄目ですとか、ご教示を頂けますと幸いです。よろしくお願い致します。
import UIKit class sampleview:UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate,UITableViewDataSource, UITableViewDelegate{ // Sectionで表示する配列 private let mySection: NSArray = ["トピックタイトル"] @IBOutlet weak var try1: UITableView! override func viewDidLoad() { //code super.viewDidLoad() try1.dataSource = self try1.delegate = self jsontry() } // Cellで表示する配列 private let myManItems: NSArray = ["太郎", "哲也", "一郎", "宗一郎", "智","太郎", "哲也", "一郎", "宗一郎", "智"] // Sectionの数を返す func numberOfSectionsInTableView(tableView: UITableView) -> Int { return mySection.count } // Sectionの内容を返す func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return mySection[section] as? String } // Cellに表示する数を返す func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return myManItems.count }else { return 0 } } // Cellの内容を返す func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) if indexPath.section == 0{ cell.textLabel?.text = "\(myManItems[indexPath.row])" } return cell } func jsontry(){ // 通信用のConfigを生成. let myConfig:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() // Sessionを生成. let mySession:NSURLSession = NSURLSession(configuration: myConfig, delegate: self, delegateQueue: nil) // 通信先のURLを生成. let myUrl:NSURL = NSURL(string: "http://localhost/book/jsonDB.php")! // タスクの生成. let myTask:NSURLSessionDataTask = mySession.dataTaskWithURL(myUrl, completionHandler: { (data, response, err) -> Void in do{ // 受け取ったJSONデータをパースする. let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray // パースしたJSONデータへのアクセス. var number = 0 let jsoncont = json as! NSArray print(jsoncont) for value in json{ let username = value["user_name"] as! NSString print(username) number = number+1 } }catch{} }) self.try1.reloadData() myTask .resume() } }
php側のファイルとしては、データベースから情報をセレクトして、
while構文を使って、以下のような形で設定しております。
while($data = データベースセレクト構文 -> fetch_array()){ $age = $age + 1; $user_name = $data['user_name']; $senddata []= array( 'user_name'=>$data['user_name'], 'user_age'=>$age ); }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/06/04 01:57