所以我正在做一个后台获取,并且在我想更新 UI 之后。后台获取本身(数据库)有效,但是当我想更新 UI 时,我遇到了崩溃unexpectedly found nil while unwrapping an Optional value
根据我的 xCodeself.newestPublicationsCollectionView.reloadData()
是在 updateCollections() 函数中发生崩溃的地方。
func updateCollections() {
// get latest data from Database
latestPublications = getNewestPublications()
self.newestPublicationsCollectionView.reloadData()
self.newestPublicationsCollectionView.layoutIfNeeded()
// fix wrong content height
self.newestPublicationsCollectionViewHeight.constant = self.newestPublicationsCollectionView.collectionViewLayout.collectionViewContentSize().height
}
AppDelegate 中的其他代码:
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let fetchViewController = PublicationOverviewController()
fetchViewController.fetch {
dispatch_async(dispatch_get_main_queue()) {
fetchViewController.updateCollections()
}
completionHandler(.NewData)
}
}
我的 PublicationOverviewController 中的 .fetch
func fetch(completion: () -> Void) {
PublicationFetcher.shared.fetchAllPublications()
completion()
}
我认为崩溃是因为我需要主线程上的 UI,但这并没有帮助。任何输入都会很好。
细节:
在我的 PublicationFetcher.shared.fetchAllPublications() 中,我执行以下操作:
- 从后端获取数据
dispatch_async(dispatch_get_main_queue()) { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("RELOAD_NOTIFICATION", object: nil) }
在那个重新加载通知下我做了一个updateCollections()
斯威夫特 3:
DispatchQueue.global(attributes: .qosBackground).async {
print("This is run on the background queue")
DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}
}