Ios Swift DidReceiveMotonification在应用程序中启动
这是我的didReceiveMemotentification的代码:Ios Swift DidReceiveMotonification在应用程序中启动,ios,swift,swift3,push-notification,notifications,Ios,Swift,Swift3,Push Notification,Notifications,这是我的didReceiveMemotentification的代码: func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { print("notification recieved: \(userInfo)") // Pass push notification payload to the shared model
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("notification recieved: \(userInfo)")
// Pass push notification payload to the shared model
let payload: NSDictionary = userInfo as NSDictionary
if let variable = payload["variable"] as? String {
NotificationManager.SharedInstance.handleVariableNotification(variable)
}
}
当我从应用程序外部单击通知时,代码可以正常工作并完成我希望它完成的任务
我的问题是:如果我当前在应用程序中收到通知,它仍会运行通知中的代码,并覆盖用户当前在应用程序中执行的任何操作
我只希望在用户单击通知时运行代码,如果我已经在应用程序中,则不会自动运行代码
提前谢谢 将代码包装成:
if (application.applicationState != .active){}
它将检查您当前是否在应用程序中,并且仅当应用程序处于非活动状态或在后台时才会触发代码。在您的
DidReceiveMemotentification
委托方法中:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
switch application.applicationState {
case .active:
print("Application is open, do not override")
case .inactive, .background:
// Pass push notification payload to the shared model
let payload: NSDictionary = userInfo as NSDictionary
if let variable = payload["variable"] as? String {
NotificationManager.SharedInstance.handleVariableNotification(variable)
}
default:
print("unrecognized application state")
}
}
另外,如果您的应用程序是通过用户打开应用程序发送的远程通知而启动的,则您需要在应用程序中执行此操作。delegatedidFinishLaunchingWithOptions
方法:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Check to see if launchOptions contains any data
if launchOptions != nil {
// Check to see if the data inside launchOptions is a remote notification
if let remoteNotification = launchOptions![UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
// Do something with the notification
}
}
return true
}