【发布时间】:2018-02-04 16:37:35
【问题描述】:
我想从本地通知启动我的应用程序:
func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case "play":
var setAlarmVC = self.window?.rootViewController as? SettingAlarmViewController
if setAlarmVC == nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
setAlarmVC = storyboard.instantiateViewController(withIdentifier: "AlarmViewController") as? SettingAlarmViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = setAlarmVC
self.window?.makeKeyAndVisible()
}
case "snooze":
print("I pressed pause")
default:
break
}
completionHandler()
}
在我的 SettingAlarmViewController 的 viewDidLoad 中,我设置了一些简单的打印输出
override func viewDidLoad() {
super.viewDidLoad()
print("Setting Alarm View Controller was instantiated")
}
当我在应用程序处于后台时从本地通知按播放时,我按预期得到控制台打印输出:
Setting Alarm View Controller was instantiated
但应用程序并没有真正启动并且设置警报视图控制器没有出现。如果我然后点击应用程序,一个新的设置警报视图控制器是第一个可见的东西。我觉得我一定错过了一些明显的东西,但我无法弄清楚它是什么。
编辑:做更多的测试。当通知出现在锁定屏幕上并且用户在锁定屏幕上按“播放”时,密码/解锁屏幕不会出现,但应用程序仍会启动并且我得到打印输出“设置警报视图控制器已实例化”
【问题讨论】:
-
您是否尝试打印
self.window?.rootViewController的值? -
在“self.window?.makeKeyAndVisible()”之后打印出 self.window?.rootViewController 结果:“Optional()”
-
我想这就是你的 if 条件失败的原因:
if setAlarmVC == nil {} -
抱歉,我的评论不清楚。 if 条件没有失败。当我在 if 语句的末尾打印出 self.window?.rootViewController 时,我得到 "Optional()" 。在 if 语句之前我得到 nil。
-
好吧,我一天的时间都浪费在这上面了,这里的问题是其他人不会有同样的问题:developer.apple.com/documentation/usernotifications/… 你必须在通知操作中添加 [.foreground],如let playAction = UNNotificationAction(identifier: "play", title: "play", options: [.foreground])
标签: ios swift appdelegate unusernotificationcenter