186

是否可以通过推送通知知道应用程序是否已启动/打开?

我想启动事件可以在这里捕获:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}

但是,当应用程序在后台时,我如何检测它是从推送通知中打开的?

4

29 回答 29

193

请参阅此代码:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

如同

-(void)application:(UIApplication *)application didReceiveLocalNotification (UILocalNotification *)notification
于 2013-05-06T07:21:39.770 回答
132

迟到但可能有用

当应用程序未运行时

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

叫做 ..

您需要在哪里检查推送通知

NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification) {
    NSLog(@"app recieved notification from remote%@",notification);
    [self application:application didReceiveRemoteNotification:notification];
} else {
    NSLog(@"app did not recieve notification");
}
于 2014-02-06T18:26:11.313 回答
47

我们遇到的问题是在应用程序启动后正确更新视图。这里有复杂的生命周期方法序列,令人困惑。

生命周期方法

我们对 iOS 10 的测试揭示了针对各种情况的以下生命周期方法序列:

DELEGATE METHODS CALLED WHEN OPENING APP

    Opening app when system killed or user killed
        didFinishLaunchingWithOptions
        applicationDidBecomeActive

    Opening app when backgrounded
        applicationWillEnterForeground
        applicationDidBecomeActive

DELEGATE METHODS CALLED WHEN OPENING PUSH

    Opening push when system killed
        [receiving push causes didFinishLaunchingWithOptions (with options) and didReceiveRemoteNotification:background]
        applicationWillEnterForeground
        didReceiveRemoteNotification:inactive
        applicationDidBecomeActive

    Opening push when user killed
        didFinishLaunchingWithOptions (with options)
        didReceiveRemoteNotification:inactive [only completionHandler version]
        applicationDidBecomeActive

    Opening push when backgrounded
        [receiving push causes didReceiveRemoteNotification:background]
        applicationWillEnterForeground
        didReceiveRemoteNotification:inactive
        applicationDidBecomeActive

问题

好的,所以现在我们需要:

  1. 确定用户是否通过推送打开应用
  2. 根据推送状态更新视图
  3. 清除状态,以便后续打开不会将用户返回到相同位置。

棘手的一点是,必须在应用程序实际激活时更新视图,这在所有情况下都是相同的生命周期方法。

我们的解决方案草图

以下是我们解决方案的主要组成部分:

  1. notificationUserInfo在 AppDelegate 上存储一个实例变量。
  2. 设置notificationUserInfo = nilapplicationWillEnterForegrounddidFinishLaunchingWithOptions中。
  3. 设置notificationUserInfo = userInfodidReceiveRemoteNotification:inactive
  4. applicationDidBecomeActive始终调用自定义方法openViewFromNotification并传递self.notificationUserInfo. 如果self.notificationUserInfo为 nil 则提前返回,否则根据中找到的通知状态打开视图self.notificationUserInfo

解释

当从推送打开didFinishLaunchingWithOptionsapplicationWillEnterForeground总是在之前立即调用didReceiveRemoteNotification:inactive时,所以我们首先在这些方法中重置 notificationUserInfo 以便没有陈旧状态。然后,如果didReceiveRemoteNotification:inactive被调用,我们知道我们正在从推送中打开,所以我们设置self.notificationUserInfo它然后被拾取applicationDidBecomeActive以将用户转发到正确的视图。

最后一种情况是,如果用户在应用程序切换器中打开了应用程序(即在应用程序处于前台时双击主页按钮),然后收到推送通知。在这种情况下,只有didReceiveRemoteNotification:inactive被调用,WillEnterForeground 和 didFinishLaunching 都没有被调用,所以你需要一些特殊的状态来处理这种情况。

希望这可以帮助。

于 2017-01-31T22:49:38.183 回答
27

这是一篇陈旧的帖子......但它仍然缺少解决问题的实际解决方案(正如各种评论中所指出的那样)。

最初的问题是关于检测应用程序何时从推送通知启动 /打开,例如用户点击通知。没有一个答案实际上涵盖了这种情况。

原因可以在通知到达时的调用流程中看到,application:didReceiveRemoteNotification...

当收到通知在用户点击通知时再次调用。因此,您无法仅通过查看UIApplicationState用户是否点击它来判断。

此外,您不再需要处理在 iOS 9+(也可能是 8)启动后再次调用的应用application:didFinishLaunchingWithOptions...程序“冷启动”的情况。application:didReceiveRemoteNotification...

那么,如何判断用户点击是否启动了事件链呢?我的解决方案是标记应用程序开始退出后台或冷启动的时间,然后在application:didReceiveRemoteNotification.... 如果小于 0.1s,那么你可以很确定点击触发了启动。

斯威夫特 2.x

class AppDelegate: UIResponder, UIApplicationDelegate {

  var wakeTime : NSDate = NSDate()        // when did our application wake up most recently?

  func applicationWillEnterForeground(application: UIApplication) {    
    // time stamp the entering of foreground so we can tell how we got here
    wakeTime = NSDate()
  }

  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // ensure the userInfo dictionary has the data you expect
    if let type = userInfo["type"] as? String where type == "status" {
      // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
      if application.applicationState != UIApplicationState.Background && NSDate().timeIntervalSinceDate(wakeTime) < 0.1 {
        // User Tap on notification Started the App
      }
      else {
        // DO stuff here if you ONLY want it to happen when the push arrives
      }
      completionHandler(.NewData)
    }
    else {
      completionHandler(.NoData)
    }
  }
}

斯威夫特 3

class AppDelegate: UIResponder, UIApplicationDelegate {

    var wakeTime : Date = Date()        // when did our application wake up most recently?

    func applicationWillEnterForeground(_ application: UIApplication) {
      // time stamp the entering of foreground so we can tell how we got here
      wakeTime = Date()
    }

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

      // ensure the userInfo dictionary has the data you expect
      if let type = userInfo["type"] as? String, type == "status" {
        // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
        if application.applicationState != UIApplicationState.background && Date().timeIntervalSince(wakeTime) < 0.1 {
          // User Tap on notification Started the App
        }
        else {
          // DO stuff here if you ONLY want it to happen when the push arrives
        }
        completionHandler(.newData)
      }
      else {
        completionHandler(.noData)
      }
    }
}

我已经在 iOS 9+ 上对这两种情况(后台应用程序,应用程序未运行)进行了测试,它就像一个魅力。0.1s 也相当保守,实际值约为 0.002s,所以 0.01 也可以。

于 2016-07-28T20:00:18.390 回答
25

当应用程序终止时,用户点击推送通知

public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
   if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
      print("from push")
    }
}

当应用程序处于后台时,用户点击推送通知

如果用户从系统显示的警报中打开您的应用程序,系统可能会在您的应用程序即将进入前台时再次调用此方法,以便您可以更新用户界面并显示与通知有关的信息。

public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
  if application.applicationState == .inactive {
    print("from push")
  }
}

根据您的应用程序,它还可以通过content-availableinside向您发送静默推送aps,因此也要注意这一点 :) 请参阅https://stackoverflow.com/a/33778990/1418457

于 2016-06-22T12:13:02.403 回答
19

Swift 2.0 用于“未运行”状态(本地和远程通知)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


// Handle notification
if (launchOptions != nil) {

    // For local Notification
    if let localNotificationInfo = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {

        if let something = localNotificationInfo.userInfo!["yourKey"] as? String {
            self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
        }


    } else

    // For remote Notification
    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject]? {

        if let something = remoteNotification["yourKey"] as? String {
            self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
        }
    }

}


return true
}
于 2016-02-11T11:27:12.573 回答
15

检查您的应用程序在application:didReceiveRemoteNotification:前台或后台时是否收到通知。

如果在后台收到,请从通知中启动应用程序。

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        NSLog(@"Notification received by running app");
    } else {
        NSLog(@"App opened from Notification");
    }
}
于 2013-05-06T07:25:15.807 回答
15

对于快速:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    PFPush.handlePush(userInfo)

    if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {
        //opened from a push notification when the app was in the background

    }

}
于 2014-11-29T23:34:28.210 回答
4

是的,您可以在appDelegate中通过此方法检测:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
      /* your Code*/
}

对于本地通知:

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
         /* your Code*/
}
于 2013-05-06T07:13:00.820 回答
4

为 Xamarin 用户发布此内容。

检测应用程序是否通过推送通知启动的关键是AppDelegate.FinishedLaunching(UIApplication app, NSDictionary options)方法和传入的选项字典。

如果它是本地通知,则选项字典将包含此键: UIApplication.LaunchOptionsLocalNotificationKey

如果是远程通知,它将是UIApplication.LaunchOptionsRemoteNotificationKey.

当键是LaunchOptionsLocalNotificationKey时,对象是类型UILocalNotification。然后,您可以查看通知并确定它是哪个特定通知。

专业提示:UILocalNotification其中没有标识符,方式相同UNNotificationRequest。在包含 requestId 的 UserInfo 中放置一个字典键,以便在测试时UILocalNotification,您将有一个特定的 requestId 可用于基于某些逻辑。

我发现即使在 iOS 10+ 设备上使用UNUserNotificationCenter's AddNotificationRequest&创建位置通知UNMutableNotificationContent时,当应用程序未运行(我杀死它)并通过点击通知中心的通知启动时,字典仍然包含UILocalNotificaiton对象。

这意味着我检查基于通知的启动的代码将适用于 iOS8 和 iOS 10+ 设备

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
    _logger.InfoFormat("FinishedLaunching");

    if(options != null)
    {
        if (options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey))
        {
            //was started by tapping a local notification when app wasn't previously running.
            //works if using UNUserNotificationCenter.Current.AddNotificationRequest OR UIApplication.SharedApplication.PresentLocalNotificationNow);

            var localNotification = options[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification;

            //I would recommended a key such as this :
            var requestId = localNotification.UserInfo["RequestId"].ToString();
        }               
    }
    return true;
}
于 2018-01-19T20:53:56.007 回答
3

如果有人想要 swift 3 中的答案

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    switch application.applicationState {
    case .active:
        //app is currently active, can update badges count here
        break
    case .inactive:
        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
        break
    case .background:
        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
        break
    default:
        break
    }
}
于 2016-12-21T09:15:17.473 回答
3

如果您运行的是iOS 13或更高版本,请在SceneDelegate 中使用此代码:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let notificationResponse = connectionOptions.notificationResponse else { return }
    
    let pushTitle = notificationResponse.notification.request.content.title
    let pushSubtitle = notificationResponse.notification.request.content.subtitle
    let pushBody = notificationResponse.notification.request.content.body
    
    // do your staff here
}
于 2020-10-07T17:07:33.157 回答
2

直接来自文档

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo:nil

如果应用正在运行并收到远程通知,应用会调用此方法处理通知。

您对此方法的实现应使用通知来采取适当的行动。

稍晚一点

如果推送通知到达时应用程序未运行,则该方法将启动应用程序并在启动选项字典中提供适当的信息。

该应用程序不会调用此方法来处理该推送通知。

相反,您对

application:willFinishLaunchingWithOptions:

或者

application:didFinishLaunchingWithOptions:

方法需要获取推送通知有效负载数据并适当响应。

于 2013-05-06T07:23:00.207 回答
2
于 2017-11-16T09:06:34.020 回答
2

M.Othman 的答案对于不包含场景委托的应用程序是正确的 对于场景委托应用程序这在iOS 13上对我有用

这是应该在将连接场景中编写的代码

if connectionOptions.notificationResponse == nil { 
//Not opened from push notification
} else {
  //Opened from push notification
}

用于支持早期版本的应用程序委托的代码 didFinishLaunchingWithOptions

let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]
        if (notification != nil) {

            //Launched from push notification
        } else {

            //Launch from other source
        }
于 2020-03-31T13:09:37.627 回答
1
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    print("Push notification received: \(data)")

    if let info = data["aps"] as? Dictionary<String, AnyObject> {
        let alertMsg = info["alert"] as! String
        print(alertMsg)
        switch application.applicationState {
        case .active:
            print("do stuff in case App is active")
        case .background:
            print("do stuff in case App is in background")
           // navigateToChatDetailViewControler(pushdata: data)
        case .inactive:
            print("do stuff in case App is inactive")
            // navigateToChatDetailViewControler(pushdata: data)
        }
    }
}
于 2018-05-31T12:35:50.610 回答
1

只有一种可靠的方法,它仅适用于iOS 10+

使用UNUserNotificationCenter实现UNUserNotificationCenterDelegate方法:

- (void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {

    //Here you can get your original push if you need to
    NSDictionary* pusDict = response.notification.request.content.userInfo;

    if ([response.actionIdentifier isEqualToString: UNNotificationDefaultActionIdentifier]) {
        //User tapped the notification
    } else if ([response.actionIdentifier isEqualToString: UNNotificationDismissActionIdentifier]) {
        //User dismissed the notification 
    } else if ([response.actionIdentifier isEqualToString: MYCustomActionId]) {
        //User chose my custom defined action
    }
    ...
}
于 2018-06-28T08:27:09.980 回答
1

2021,Swift 5,仅限本地通知

UNUserNotificationCenter.current().delegate = self

extension YourClass: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let notificationIdentifier = response.notification.request.identifier

        // If this is called, then your app was opened from a local notification with this identifier
    }
}


于 2021-07-16T15:33:17.820 回答
0
     // shanegao's code in Swift 2.0
     func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
    {
            if ( application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background ){
                    print("opened from a push notification when the app was on background")
            }else{
                    print("opened from a push notification when the app was on foreground")
            }
    }
于 2016-03-16T19:35:11.770 回答
0

这个问题的问题在于“打开”应用程序的定义不明确。应用程序要么从非运行状态冷启动,要么从非活动状态重新激活(例如,从另一个应用程序切换回它)。这是我区分所有这些可能状态的解决方案:

typedef NS_ENUM(NSInteger, MXAppState) {
    MXAppStateActive = 0,
    MXAppStateReactivated = 1,
    MXAppStateLaunched = 2
};

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ... your custom launch stuff
    [[MXDefaults instance] setDateOfLastLaunch:[NSDate date]];
    // ... more custom launch stuff
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Through a lot of trial and error (by showing alerts), I can confirm that on iOS 10
    // this method is only called when the app has been launched from a push notification
    // or when the app is already in the Active state.  When you receive a push
    // and then launch the app from the icon or apps view, this method is _not_ called.
    // So with 99% confidence, it means this method is called in one of the 3 mutually exclusive cases
    //    1) we are active in the foreground, no action was taken by the user
    //    2) we were 'launched' from an inactive state (so we may already be in the main section) by a tap
    //       on a push notification
    //    3) we were truly launched from a not running state by a tap on a push notification
    // Beware that cases (2) and (3) may both show UIApplicationStateInactive and cant be easily distinguished.
    // We check the last launch date to distinguish (2) and (3).

    MXAppState appState = [self mxAppStateFromApplicationState:[application applicationState]];
    //... your app's logic
}

- (MXAppState)mxAppStateFromApplicationState:(UIApplicationState)state {
    if (state == UIApplicationStateActive) {
        return MXAppStateActive;
    } else {
        NSDate* lastLaunchDate = [[MXDefaults instance] dateOfLastLaunch];
        if (lastLaunchDate && [[NSDate date] timeIntervalSinceDate:lastLaunchDate] < 0.5f) {
            return MXAppStateLaunched;
        } else {
            return MXAppStateReactivated;
        }
    }
    return MXAppStateActive;
}

并且MXDefaults只是NSUserDefaults.

于 2017-03-14T14:00:09.347 回答
0

Xcode 10 斯威夫特 4.2

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    let state : UIApplicationState = application.applicationState
    if (state == .Inactive || state == .Background) {
        // coming from background
    } else {
        // App is running in foreground
    }
}
于 2019-06-20T10:38:00.647 回答
0

M.Othman 对 Swift 5 的回答。(尽管不再推荐使用 NSLog )

在设置显示RootViewController. 在您的application(_:didReceiveRemoteNotification)中,您应该添加可以区分首次启动和后台启动类型的逻辑。

if let launchOptions = launchOptions, 
let notification = launchOptions[UIApplicationLaunchOptionsKey.remoteNotification] 
as? [AnyHashable : Any] {
    NSLog("app recieved notification from remote \(notification)")
    self.application(application, didReceiveRemoteNotification: notification)
} else {
    NSLog("app did not recieve notification")
}

可以在以下位置找到解决此问题的其他一些 Swift 特定答案:点击通知时如何处理 Swift 3 中的启动选项?遇到语法问题

于 2021-02-01T08:51:11.623 回答
0

如果您SceneDelegate的应用程序中有,那么您应该使用以下代码来管理本地/远程通知,当您的应用程序被终止/终止并且您通过点击通知打开应用程序时

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    //Handle Notification Response
    guard let notifiResponse = connectionOptions.notificationResponse else { return }
    
    if notifiResponse.notification.request.trigger is UNTimeIntervalNotificationTrigger { //Local Notification
        Messaging.messaging().appDidReceiveMessage(notifiResponse.notification.request.content.userInfo)
        
        print("Receive Local Notifications")            
    }
    else if notifiResponse.notification.request.trigger is UNPushNotificationTrigger{ //Remote Notification
        
        print("Receive Remote Notifications")
    }                
}

当您的应用程序处于后台/前台状态时,使用您AppDelegate来管理本地/远程通知。

extension AppDelegate : UNUserNotificationCenterDelegate {   

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
                   
        if response.notification.request.trigger is UNTimeIntervalNotificationTrigger{
             print("Receive Local Notifications")
        }
        else if response.notification.request.trigger is UNPushNotificationTrigger{
             print("Receive Remote Notifications")
        }
    
        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       print("willPresent Notifications")

       if notification.request.trigger is UNTimeIntervalNotificationTrigger{
            print("Receive Local Notifications")
       }
       else {
            print("Receive Remote Notifications")
       }
       completionHandler([.banner, .list, .sound])
    }
}
于 2022-02-11T10:28:45.720 回答
-1

您可以使用:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

处理远程推送通知。

在这里查看文档

于 2013-05-06T07:12:39.460 回答
-1

我还没有尝试过,但也许你可以给自己发个通知?http://nshipster.com/nsnotification-and-nsnotificationcenter/

于 2015-02-10T15:27:52.333 回答
-1

为了swift

 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){

    ++notificationNumber
    application.applicationIconBadgeNumber =  notificationNumber;

    if let aps = userInfo["aps"] as? NSDictionary {

        var message = aps["alert"]
        println("my messages : \(message)")

    }
}
于 2015-08-21T15:01:07.823 回答
-1

对于 Swift 用户:

如果您想从 push 或类似的东西打开时启动不同的页面,您需要像这样签入didFinishLaunchingWithOptions

let directVc: directVC! = directVC(nibName:"directVC", bundle: nil)
let pushVc: pushVC! = pushVC(nibName:"pushVC", bundle: nil)

if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
     self.navigationController = UINavigationController(rootViewController: pushVc!)
} else {
     self.navigationController = UINavigationController(rootViewController: directVc!)
}
self.window!.rootViewController = self.navigationController
于 2016-01-13T21:22:30.427 回答
-1

当应用程序在后台作为shanegao时,您可以使用

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

但是,如果您想启动应用程序并且当应用程序关闭并且您想调试您的应用程序时,您可以转到编辑方案并在左侧菜单中选择运行,然后在启动中选择等待可执行文件启动,然后您的应用程序在您启动时启动点击推送通知

编辑方案 > 运行 > 等待可执行文件启动

于 2017-11-16T09:47:42.017 回答
-2

迅速:

我正在运行推送通知(带有后台获取)。当我的应用在后台并收到推送通知时,我发现 appDelegate 中的 didReceiveRemoteNotification 会被调用两次;一次是在收到通知时,另一次是在用户单击通知警报时。

要检测是否单击了通知警报,只需检查 appDelegate 中的 didReceiveRemoteNotification 中的 applicationState 原始值是否 == 1。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) {
    // If not from alert click applicationState(1)
    if (application.applicationState.rawValue != 1) {
        // Run your code here
    }
}

我希望这有帮助。

于 2016-10-07T09:14:39.920 回答