我正在开发一个项目,但很难收到通知带我到我的“NotiViewController”。有时它可以按预期工作,但有时它只是打开我的应用程序到我最后一次使用的viewController。
我将这些代码整合到一些在线资源中:
extension QuestionViewController: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:
UNNotificationResponse, withCompletionHandler completionHandler: @escaping () ->
Void) {
let vc = storyboard?.instantiateViewController(withIdentifier: "NotiViewControllerID")
as! NotiViewController
show(vc, sender: Any?.self)
completionHandler()
}
我希望能够发送一个通知,询问用户一个问题,然后点击后让用户接听答案......
例如,通知问题:“美国有多少州?” =>点击通知=>加载适当的NotiViewController:“48”
答案 0 :(得分:0)
试试这段代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//when application is close
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable : Any] {
print(userInfo)
self.getBGUserInfo(userInfo: userInfo)
// if notification call to redirect perticular page
}
}
func getBGUserInfo(userInfo : [AnyHashable : Any] ) {
//get userInfo details here
NotificationCenter.default.post(name: Notification.Name(rawValue: "NotificationRedirect"), object: nil)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
NotificationCenter.default.post(name: Notification.Name(rawValue: "NotificationRedirect"), object: nil)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
NotificationCenter.default.post(name: Notification.Name(rawValue: "NotificationRedirect"), object: nil)
}
//In ViewController which open first while open app
//In ViewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(self.receiveTestNotification(_:)), name: NSNotification.Name(rawValue: "NotificationRedirect"), object: nil)
//Over
func receiveTestNotification(_ notification: Notification) {
let notName : String = String(describing: notification.name.rawValue)
if (notName == "NotificationRedirect"){
//Redirect your NotiViewController
}
}