iOS Firebase消息传递无法接收

时间:2017-07-27 10:46:51

标签: ios firebase swift3 apple-push-notifications firebase-cloud-messaging

我今天和昨天一直在打破这个问题,因为某些原因我的iOS应用程序没有收到任何firebase通知。据我所知,我已经做了应有的一切。

  • 我已经检查了Apple开发者帐户中的认证,所有内容都已正确设置(参见屏幕截图)。
  • 我在物理设备上进行测试
  • Firebase已正确设置,日志显示已正确连接到firebase
  • 我在项目的功能选项卡中启用了推送通知,后台提取和远程通知
  • 我已将Apple APN键从Apple控制台添加到Firebase

通过Firebase控制台向主题或所有iOS应用发送通知时,没有任何反应。我有相同的应用程序在Android上顺利运行,在目标时接收所有通知。

AppDelegate.swift

//
//  AppDelegate.swift
//  CoyoteBreda
//
//  Created by Milan van Dijck on 28/02/2017.
//  Copyright © 2017 Miscoria web development. All rights reserved.
//

import UIKit
import GoogleMaps
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        GMSServices.provideAPIKey("AIzaSyB2JNmY2D6q7lYKmJmyeeDXdk-ILEM4q1Q")
        UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)

        //Initialize firebase
        //FIRApp.configure()

        do {
            Network.reachability = try Reachability(hostname: "www.google.com")
            do {
                try Network.reachability?.start()
            } catch let error as Network.Error {
                print(error)
            } catch {
                print(error)
            }
        } catch {
            print(error)
        }

        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification),
                                                         name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        return true
    }

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        // -----------------------
        // FIREBASE MESSAGING
        // -----------------------
        FIRApp.configure()

        application.registerForRemoteNotifications()
        requestNotificationAuthorization(application: application)

        if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] {
            NSLog("[RemoteNotification] applicationState: \(applicationStateString) didFinishLaunchingWithOptions for iOS9: \(userInfo)")
            //TODO: Handle background notification
        }


        application.registerForRemoteNotifications()

        return true;
    }

    func tokenRefreshNotification(notification: NSNotification)
    {
        if let refreshedToken = FIRInstanceID.instanceID().token()
        {
            print("InstanceID token: \(refreshedToken)")
        }
        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
    {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox)
        FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod)
    }

    func connectToFcm()
    {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil)
            {
                print("[Unable to connect with FCM. \(String(describing: error))]")
            }
            else
            {
                print("[Connected to FCM.]")
            }
        }
    }

    var applicationStateString: String {
        if UIApplication.shared.applicationState == .active {
            return "active"
        } else if UIApplication.shared.applicationState == .background {
            return "background"
        }else {
            return "inactive"
        }
    }

    func requestNotificationAuthorization(application: UIApplication) {
        if #available(iOS 10.0, *) {
            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)
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("[REGISTERING FOR TOPICS]")
        FIRMessaging.messaging().subscribe(toTopic: "/topics/activiteit")
        FIRMessaging.messaging().subscribe(toTopic: "/topics/message")
    }

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        // Update the database
        DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: completionHandler)

        // TODO: update views

        //completionHandler(.newData)
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        connectToFcm()

        DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: {(result: UIBackgroundFetchResult) -> Void in
            NSLog("Done updating!")
        })
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

@available(iOS 10, *)
extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }


}

extension AppDelegate : UNUserNotificationCenterDelegate {
    // iOS10+, called when presenting notification in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)")
        //TODO: Handle foreground notification
        completionHandler([.alert])
    }

    // iOS10+, called when received response (default open, dismiss or custom action) for a notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) didReceiveResponse: \(userInfo)")
        //TODO: Handle background notification
        completionHandler()
    }
}

应用输出: Application output

Apple证书:

Provisioning profile

Provisioning profile selection

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

试试这个

 import UIKit
 import Firebase
 import FirebaseMessaging
 import UserNotifications

 @UIApplicationMain
 class AppDelegate: UIResponder,UIApplicationDelegate,UNUserNotificationCenterDelegate{

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //create the notificationCenter







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

    FirebaseApp.configure()

    return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("Registration succeeded! Token: ", token)
}

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













func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

// Firebase notification received
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

   // let dict = notification.request.content.userInfo["aps"] as! NSDictionary

 //  print(dict)

 //        let d : [String : Any] = dict["alert"] as! [String : Any]
 //        let body : String = d["body"] as! String
 //        let title : String = d["title"] as! String

 //        
   //        print("Title:\(title) + body:\(body)")
  //      
  //        
  //        
  //        self.showAlertAppDelegate(title:    title,message:body,buttonTitle:"ok",window:self.window!)


    completionHandler(.alert)


}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background


    if response.actionIdentifier == "goToApp"{

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = nextViewController


    }else if response.actionIdentifier == "cancel" {

    print("close")

    }else {






    }



    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here

}

答案 1 :(得分:0)

正如您所说,您在Android中收到通知并遇到iOS问题,因此有可能因为Payload格式而出现此问题。我之前也遇到过这个问题。

请确保您的Payload格式必须如下所示。

{
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }

如果您的应用在ios 10或更高版本上运行,请确保设置delegate

有关详细信息,请参阅here