Удаленные уведомления из фона - PullRequest
0 голосов
/ 22 октября 2018

Я создаю приложение в swift, которое будет использовать кнопки UNNotificationAction.

У меня userNotificationCenter настроен правильно, и я могу правильно вызывать didReceive, пока приложение открыто ... ОтсюдаЯ показываю модальное окно.

Проблема в том, что когда приложение не работает на переднем или заднем плане (пользователь еще не открыл приложение), я не могу получить didFinishLaunchingWithOptions для анализа своего кода при проверкена launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]

Существует ли новый метод обработки, когда пользователь заново открывает приложение при нажатии на push-уведомление, используя UNNotificationAction?

Ответы [ 2 ]

0 голосов
/ 22 октября 2018

Пожалуйста, проверьте этот код ниже, надеюсь, это поможет.

     @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.registerForRemoteNotifications()
    }



   @available(iOS 10, *)

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
     Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // print(userInfo)
      completionHandler([.alert, .badge, .sound])
    // Change this to your preferred presentation option
   // completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    switch response.actionIdentifier {
    case "action1":
        print("Action First Tapped")
    case "action2":
        print("Action Second Tapped")
    default:
        break
    }

    // Print full message.
    print(userInfo)
    Messaging.messaging().appDidReceiveMessage(userInfo)
    completionHandler()
}
0 голосов
/ 22 октября 2018

В didFinishLaunchingWithOptions, когда вы обнаружите, что запускаете из-за уведомления, установите себя как UNUserNotificationCenter на delegate и верните false.Теперь будет вызвана ваша didReceive реализация.

...