【发布时间】:2017-05-24 18:03:02
【问题描述】:
我向 Firebase 发送了一些信息,如果成功,回调中可能会发生 5 件事,如果不成功,可能会发生 3 件事:
如果成功:
活动指示器被关闭
具有日期更新的类级别变量
会出现一条警报,其中包含该变量的消息
向另一个 vc 执行推送
sendButton 再次启用(一旦按下它就被禁用)
如果不成功:
活动指示器被关闭
会出现一条警报,并显示一条消息,指出它不成功
sendButton 再次启用(一旦按下它就被禁用)
当我尝试将 navigationController?.pushViewController 放在 mainQueue 上时,它总是有问题,特别是它并不总是执行。
//caused problems
DispatchQueue.main.async {
navigationController?.pushViewController(nextVC, animated: false)
}
一旦我将它取下并留在后台,它运行得非常好。我知道我应该更新警报,但是警报使用的类级别变量和关闭活动指示器呢?
Firebase 代码:
@IBOutlet weak fileprivate var sendButton: UIButton!
let date = Date() //formatted in viewDidLoad
var todaysDate = ""
let activityIndicator = UIActivityIndicatorView() //formatted in viewDidLoad
@IBAction fileprivate func sendButtonTapped(_ sender: UIButton){
sendButton.isEnabled = false
view.addSubview(activityIndicator)
//dict has some values
nextVCRef?.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
if error != nil{
DispatchQueue.main.async {
self.activityIndicator.removeFromSuperView
self.alertError()
self.sendButton.isEnabled = true//i normally would put this is the alertError action but for clarity i put it here
}
return
}
DispatchQueue.main.async {
self.todaysDate = self.date
self.alertSuccessful()//everything happens in the function
}
})
}
fileprivate alertSuccessful(){
self.activityIndicator!.removeFromSuperView
let alert = UIAlertController(title: "Thank You!", message: "Today's date is \(self.todaysDate).", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){
(action) in
self.sendButton.isEnabled = true
_ = self.navigationController?.pushViewController(nextVC, animated: false)
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
fileprivate alertError(){
let alert = UIAlertController(title: "Unknown Error!", message: "There was an error. Try again.", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
问题是在设置变量、关闭活动指示器、出现警报、重新启用 sendButton 以及执行推送之间,应该和不应该 在主队列中?
顺便说一句,我不需要在后台更新日期变量,但在另一种情况下,我可能会从 Firebase 中提取一些信息,并且该变量将在回调中更新。我没有包含该代码,而是使用了它,因为重点是类变量是否应该在后台线程的主队列上更新?
【问题讨论】:
-
关于 UI 的所有内容都必须在主队列中。
-
@shallowThought 甚至变量和导航推送(它们不在实际的用户界面上)?
-
UINavigationController推送UIViewController。两者的名称中都有“UI”。他们不能更“在实际的用户界面上”。 -
@shallowThought ahhhhhhhhhhh,现在这很有见地。我从没想过它们以“UI”开头。谢谢!为什么你认为我在主队列上推动导航时遇到了问题,但一旦我将其关闭,所有问题都停止了?
-
顺便说一下,Firebase completion blocks 总是在 主队列 上调用,因此您无需将这些调用包装在
DispatchQueue.main完全 :-)
标签: swift asynchronous firebase firebase-realtime-database grand-central-dispatch