Firebase - Push-уведомления - не работает - PullRequest
0 голосов
/ 27 ноября 2018

Я просто пробую Push-уведомления с помощью Firebase;Вначале я следовал этому документу: https://www.appcoda.com/firebase-push-notifications/

Вот соответствующий код, который у меня есть на данный момент: (Он собирается без каких-либо проблем)

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ......
    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    ......

    return true
}

......

// The callback to handle data message received via FCM for devices running iOS 10 or above.
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
    print(#function)
    print(remoteMessage.appData)
}

Когда я пытаюсь его протестировать(следуя советам в документе, упомянутом ранее), функция applicationReceivedRemoteMessage () никогда не вызывается, и я ничего не вижу.Что мне не хватает?Есть что-то, на что я должен сначала взглянуть?

Для информации, я использую Xcode Version 10.1, iOS 12.1 и Swift 4.2.

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Привет Мишель,

На основании вашей ссылочной ссылки кажется, что вы пропустили эту строку

FIRMessaging.messaging().remoteMessageDelegate = self
   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 })
        // For iOS 10 data message (sent via FCM
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    FIRApp.configure()
0 голосов
/ 27 ноября 2018

Проверьте этот код ниже:

import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     setupFireBase(application)
}

func setupFireBase(_ application: UIApplication) {
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

    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()
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    print(messaging)
    ClassUserDefault.shared.deviceToken = fcmToken
    let dataDict: [String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
    connectToFcm()
}

// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instange ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
    connectToFcm()
}

func connectToFcm() {
    InstanceID.instanceID().instanceID { (result, error) in
        if let _ = error {
            return
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
}

func application(application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    Messaging.messaging().apnsToken = deviceToken as Data
}

public func application(received remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
    completionHandler([UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge])
    print("Handle push from background or closed")
    print("\(notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: notification.request.content.userInfo)
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

    if notification.request.content.userInfo.isEmpty {
        return
    } else {
    }
    print(_ResponsePush)
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Handle push from background or closed")
    print("\(response.notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: response.notification.request.content.userInfo)
    if response.notification.request.content.userInfo.isEmpty { return } else {
        handlePush(userInfo: _ResponsePush)
    }
    print(_ResponsePush)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
    var token = ""
    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [chars[i]])
    }
    print("Device Token = ", token)
}

func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}

func handlePush(userInfo: ClassResponsePush) {

}
}

Не забудьте добавить файл .p12 в облачные сообщения о настройках проекта в консоли Firebase.

Надеюсь, это поможет:)

...