swift入門者です。今サーバーのデータベースの情報をUICollectionViewCellに持ってくる作業をやっているのですが。なぜかうまくいきません。下のコードでは問題なく動くのですが、、、
import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var myCollectionView: UICollectionView! var articleArray:[Dictionary<String,String>] = [] override func viewDidLoad() { super.viewDidLoad() accessJSON() } /*===========================セル==================================*/ //セルの数 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return articleArray.count } //セルの内容 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell cell.myLabel.text = articleArray[indexPath.item]["title"] return cell } /*============================データベース=================================*/ func accessJSON(){ let urlStr = "自分のURL" if let url = NSURL(string: urlStr) { let urlSession = NSURLSession.sharedSession() let task = urlSession.dataTaskWithURL(url, completionHandler: self.getJSON) task.resume() } } func getJSON(data: NSData?, res: NSURLResponse?, error: NSError?){ do { let jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray for (var i=0; i<jsonArray.count; i++) { var articleDic:[String:String] = [:] if let id = jsonArray[i]["id"] as? String{ articleDic["id"] = id } if let title = jsonArray[i]["title"] as? String{ articleDic["title"] = title } if let image = jsonArray[i]["image"] as? String{ articleDic["image"] = image } articleArray.append(articleDic) } dispatch_async(dispatch_get_main_queue()){ print(self.articleArray) self.myCollectionView.reloadData() } } catch { print("エラー") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
上のコードでは問題なく動くのですが、コードが複雑になってデータベースからJSONの情報を取ってくる部分だけをModel.swiftにまとめようとしたとき、UICollectionViewが更新されないです(やろうとしていることは上と同じです)。エラーが出るのは下のコードです。
Model.swift
import UIKit class Model: NSObject { var articleArray: [Dictionary<String,String>] = [] func accessJSON(){ let urlStr = "http://steins-t.com/kuchiren5/api.php?json" if let url = NSURL(string: urlStr) { let urlSession = NSURLSession.sharedSession() let task = urlSession.dataTaskWithURL(url, completionHandler: self.getJSON) task.resume() } } func getJSON(data: NSData?, res: NSURLResponse?, error: NSError?){ do { let jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray for (var i=0; i<jsonArray.count; i++) { var articleDic:[String:String] = [:] if let id = jsonArray[i]["id"] as? String{ articleDic["id"] = id } if let title = jsonArray[i]["title"] as? String{ articleDic["title"] = title } if let image = jsonArray[i]["image"] as? String{ articleDic["image"] = image } articleArray.append(articleDic) } dispatch_async(dispatch_get_main_queue()){ let hoge = ViewController() //↓ここでエラーが出る!!! hoge.myCollectionView.reloadData() } } catch { print("エラー") } } }
ViewController.swift
import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var myCollectionView: UICollectionView! //var articleArray:[Dictionary<String,String>] = [] override func viewDidLoad() { super.viewDidLoad() //Modelクラスのオブジェクトを作ってaccessJSONプロパティを実行 let model = Model() model.accessJSON() } /*===========================セル==================================*/ //セルの数 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } //セルの内容 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell cell.myLabel.text = "テスト" return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
なにか良い方法はないのでしょうか?みなさんの知恵をぜひお借りしたいです(>.<);;
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。