Как получить push-уведомления, когда приложение неактивно ios swift3 - PullRequest
0 голосов
/ 11 октября 2018

Я могу получать push-уведомления, когда приложение открыто.но когда родное приложение My iOS находится в неактивном состоянии, уведомления не запускаются.Я также поделился своим исходным кодом.кто-нибудь может подсказать мне, как выполнить эту задачу?

extension AppDelegate : MessagingDelegate {
  // [START refresh_token]
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
  }

  func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
    //creating the notification content
    let content = UNMutableNotificationContent()
    content.userInfo = ["title": remoteMessage.appData["title"] as Any]
    content.subtitle = (content.userInfo["title"] as? String)!
    // content.body = (content.userInfo["message"] as? String)!
    content.badge = 1
    content.sound = UNNotificationSound.default()
    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    UNUserNotificationCenter.current().delegate = self
    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  }
}

1 Ответ

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

Вам необходимо выполнить следующие шаги:

Зарегистрироваться для push-уведомлений:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        setupNotifications(application)

        return true
    }

    func setupNotifications(_ application: UIApplication) {

        let center  = UNUserNotificationCenter.current()
        center.delegate = self

        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in }

        application.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Notifications registration succeeded!")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Notifications registration failed!")
    }

}

2) Методы делегирования

extension AppDelegate: UNUserNotificationCenterDelegate {

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

        //Notification message clicked
    }

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

        completionHandler([.alert, .badge, .sound])
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...