Ios 通过推送通知打开应用程序时调用rest api

Ios 通过推送通知打开应用程序时调用rest api,ios,swift,push-notification,usage-statistics,Ios,Swift,Push Notification,Usage Statistics,对于后端中的统计仪表板,我需要通过alamofire调用RESTAPI,通知后端用户通过推送通知打开了应用程序 如何实现这一点?我使用本地通知,因此我将给您举一个我所做工作的示例。我不知道推送通知的方式是否相同 我要做的是将appdelegate设置为符合用户通知委托 1:导入 import UserNotifications 2:添加协议 class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCen

对于后端中的统计仪表板,我需要通过alamofire调用RESTAPI,通知后端用户通过推送通知打开了应用程序


如何实现这一点?

我使用本地通知,因此我将给您举一个我所做工作的示例。我不知道推送通知的方式是否相同

我要做的是将appdelegate设置为符合用户通知委托

1:导入

import UserNotifications
2:添加协议

 class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
var notificationCenter: UNUserNotificationCenter!
3:通知中心实例

 class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
var notificationCenter: UNUserNotificationCenter!
4:初始化并设置委托

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.delegate = self

    return true  
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

       print("notification pressed") 
}
5:通知中心响应

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.delegate = self

    return true  
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

       print("notification pressed") 
}

您是否尝试过applicationWillEnterForeground或ApplicationIDBecMeactive?但我如何区分该应用是手动打开的还是通过推送通知单击打开的?我需要在我的仪表板中查看推送是否有效。“通过推送通知单击”这是什么意思?请尝试使用UNUserNotificationCenterDelegate-userNotificationCenter(center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completionHandler:@escaping()->Void)@Lucaspalian我可以将此代码放置在哪里?我猜ViewController在应用程序的状态(冷启动或后台)方面可能有所不同。您可以在单独的类中执行相同的操作(添加noti center委托),但需要在appDelegate中保持其实例化。希望有帮助!贡献很大,非常详细!但必须指出的是,这只适用于iOS 10或更高版本。哦,是的,是的,我很抱歉:(你知道iOS 9中的情况吗?我不知道,但你可以在应用程序委托中尝试:func应用程序(u应用程序:UIApplication,didReceive通知:UILocalNotification)。看这个问题可能对你有帮助: