2017-05-30 18 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 –

相關問題