我希望在用户收到通知时切换App Delegate中的根视图。现在,我的工作,但时机已关闭。一旦我生成通知并安排它,观察者就会触发其Selector方法,过早地更改布尔值。通知将在未来启动20秒。
我使用名为StatusOverseer
的单身来指导通知并查看切换。我把它放在init()
:
// Notification Observation
NSNotificationCenter.defaultCenter().addObserver(self, selector: "bankDidApprove", name: "bankApproval", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "bankDidNotApprove", name: "bankNoApproval", object: nil)
这是StatusOverseer
生成通知的方法:
func generateNotification(isGood: Bool) {
if !setNotification && userDidFinishApplication {
let currentTime = NSDate()
let fireTime = NSDate(timeInterval: 20.0, sinceDate: currentTime)
var notification = UILocalNotification()
if isGood {
notification.alertBody = "Congratulations! You've been approved!"
notificationWasGood = true
NSNotificationCenter.defaultCenter().postNotificationName("bankApproval", object: nil)
}
else {
notification.alertBody = "Bank Status is available"
notificationWasGood = false
NSNotificationCenter.defaultCenter().postNotificationName("bankNoApproval", object: nil)
}
notification.alertAction = "open"
notification.fireDate = fireTime
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
setNotification = true
println("Notification Set")
}
}
选择器方法:
func bankDidApprove() {
println("Banks approved")
banksDidRespond = true
notificationWasGood = true
}
func bankDidNotApprove() {
println("Banks no approved")
banksDidRespond = true
notificationWasGood = false
}
我在applicationWillEnterForeground
:
var so = StatusOverseer.sharedOverseer
// Decide whether or not to present the waiting view
if so.userDidFinishApplication && !StatusOverseer.sharedOverseer.banksDidRespond {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("submitWaiting") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
}
else if so.banksDidRespond {
let sb = UIStoryboard(name: "Main", bundle: nil)
if so.notificationWasGood {
let vc = sb.instantiateViewControllerWithIdentifier("approved") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
}
else {
let vc = sb.instantiateViewControllerWithIdentifier("notApproved") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
}
}
else if so.userDidAcceptTerms {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("LicenseView") as! UIViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = vc
}
那么我应该采取更好的方式吗? 谢谢!