我从互联网上获取数据,这个数据类似于慢一点
所以我必须在dispatch_get_global_queue中加载它,但是在viewDidLoad上
但是主要的问题是,如果在从互联网获取数据时加载了它将加载的collectionView或表,然后是部分的集合视图,这给我带来了零,如何使集合视图加载在dispatch_get_global_queue完成后
import UIKit
class SectionViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var sectionTab: UIImageView!
@IBOutlet weak var sectionTitle: UILabel!
var sectionsPosts:JSON!
@IBOutlet weak var collectionView: UICollectionView!
var sectionsTap:JSON!
override func viewDidLoad() {
super.viewDidLoad()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
if Reachability.isConnectedToNetwork() == true {
if let url = NSURL(string: "http://nepraswebsite.com/new_lille/mobile_api/blog/first_tab/1") {
if let data = try? NSData(contentsOfURL: url, options: []) {
self.sectionsTap = JSON(data: data)
}
}
if let newurl = NSURL(string: "http://nepraswebsite.com/new_lille/mobile_api/blog/posts_by_category/" + sections[tapIndex]["Slug"].stringValue + "/1") {
if let newdata = try? NSData(contentsOfURL: newurl, options: []) {
self.sectionsPosts = JSON(data: newdata)
}
}
self.collectionView.reloadData()
}
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionsPosts.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cellA = collectionView.dequeueReusableCellWithReuseIdentifier("postsCell", forIndexPath: indexPath) as! PostsCollectionViewCell
cellA.postImage.sd_setImageWithURL(NSURL(string: sectionsPosts[indexPath.row]["Image"].stringValue
), placeholderImage: UIImage(named: "demopic"))
cellA.postTitle.text = sectionsPosts[indexPath.row]["Title"].stringValue
return cellA
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
UIApplication.sharedApplication().openURL(NSURL(string: sectionsPosts[indexPath.row]["URL"].stringValue
)!)
}
}
答案 0 :(得分:0)
您的numberOfItemsInSection
需要知道后台任务尚未完成。一种方法是:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionPosts?.count ?? 0
// or
return sectionsPosts == nil ? 0 : sectionsPosts.count
}
当加载完成后,您可以设置此变量并调用reloadData进行显示。
然而,仍有一些问题。首先,需要在主队列上调用reloadData
,类似于:
dispatch_async(dispatch_get_main_queue(), {
self.collectionView.reloadData()
})
其次,Apple建议使用dataTaskWithURL:completionHandler:
(NSURLSession
)代替contentsOfURL:
。这将在后台线程中为您运行任务,并为您的响应代码提供完成处理程序。您可以在NSData文档here中的dataWithContentsOfURL:options:error:
部分找到此建议。