2017-05-30 61 views
1

我正在尝试动态更新一个uicollectionview。我用this amazing tutorial就如何创建一个简单的自选。数据解析后重新加载UICollection视图

它使用项目的静态数组时很好用。我的问题 - 我想要的uicollection填充数据从我的数据库解析成一个新的数组。我不知道如何在解析我的json数据后重新加载uicollection。

使用答案更新的代码:

import UIKit 

class Books: UIViewController, UICollectionViewDelegate { 

    @IBOutlet weak var bookscollection: UICollectionView! 

    var user_id: Int = 0; 

    //------------ init ---------------// 

    override func viewDidLoad() { 
     super.viewDidLoad() 

    } 

    override func viewDidAppear(_ animated: Bool) { 
     showtutorial() 
     getuserid() 
    } 


    //------------ show books ---------------// 

    var booknames = [String]() 
    var bookcolor = [String]() 
    var bookdescription = [String]() 
    var bookid = [Int]() 

    func posttoapi(){ 

     //show loading 
     LoadingOverlay.shared.showOverlay(view: self.view) 

     //send 
     let url:URL = URL(string: "http://www.url.com")! 
     let session = URLSession.shared 
     var request = URLRequest(url: url) 
     request.httpMethod = "POST" 
     request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData 
     let paramString = "user_id=\(user_id)" 
     request.httpBody = paramString.data(using: String.Encoding.utf8) 

     let task = session.dataTask(with: request as URLRequest) {(data, response, error) in 

      //hide loading 
      LoadingOverlay.shared.hideOverlayView() 

      //no response 
      guard let data = data, let _:URLResponse = response, error == nil else { 
       print("response error") 
       return 
      } 

      //response, parse and send to build 
      let json = String(data: data, encoding: String.Encoding.utf8); 
      if let data = json?.data(using: String.Encoding.utf8){ 

       let json = try! JSON(data: data) 

       for item in json["rows"].arrayValue { 

        //push data to arrays 
        self.booknames.append(item["name"].stringValue) 
        self.bookcolor.append(item["color"].stringValue) 
        self.bookdescription.append(item["description"].stringValue) 
        self.bookid.append(item["id"].int!) 

        //reload uicollection 
        DispatchQueue.main.sync(execute: { 
         self. bookscollection.reloadData() 
        }) 


       } 

      } 

     } 

     task.resume() 

    } 




    //------------ collection -------------// 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

     print("collection view code called") 
     return self.booknames.count 
    } 


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = bookscollection.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! BooksCell 
     cell.myLabel.text = self.booknames[indexPath.item] 
     cell.backgroundColor = UIColor.cyan // make cell more visible in our example project 
     return cell 
    } 


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     print("You selected cell #\(indexPath.item)!") 
    } 



    //------------ end ---------------// 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 


} 

感谢您的帮助!

+0

你需要证明'JSON'解析代码 –

+0

您是否制作为的CollectionView出口,那么请表明代码以及。 –

+0

@andehlu从数据库获取数据或获取json响应任何涉及耗时的任务的任何应该在后台工作并更新您的用户界面应在主线程上工作,因此使用调度队列来重新加载主线程上的数据。 –

回答

1

同样的问题我faced..your有很多图片的URL意味着重装牛逼

dispatch_async(dispatch_get_main_queue(), { 
    self.collectionView.reloadData() 
}) 
+0

正确答案! – salmancs43

+0

谢谢@ salmancs43 –

+0

如果正确的答案意味着PLZ把勾选标记@andehlu –

相关问题