ios - swift 2.3 中的 Xcode 8.1 推送通知与 firebase 集成没有得到?

标签 ios swift firebase push-notification firebase-cloud-messaging

我在这里使用 Xcode 8.1 和 swift 2.3 我正在使用 firebase 集成来获取推送通知。我不知道为什么我没有收到通知.. 我的代码:

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


            if #available(iOS 10.0, *) {
                let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
                UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
                    authOptions,
                    completionHandler: {_,_ in })

                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.currentNotificationCenter().delegate = self
                // For iOS 10 data message (sent via FCM)
                FIRMessaging.messaging().remoteMessageDelegate = self
                 application.registerForRemoteNotifications()

            } else
            {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()
            FIRApp.configure()

            // Add observer for InstanceID token refresh callback.
            if #available(iOS 10.0, *) {
                NSNotificationCenter.defaultCenter().addObserver(self,
                                                                 selector: #selector(self.tokenRefreshNotification),
                                                                 name: kFIRInstanceIDTokenRefreshNotification,
                                                                 object: nil)
            } else {
                // Fallback on earlier versions
            }
    return true
    }

  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

 func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
    {
        application.registerForRemoteNotifications()


    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
    {
        print(deviceToken)
        let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
        print("Device Token:", tokenString)

    }
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // Print the error to console (you should alert the user that registration failed)
        print("APNs registration failed: \(error)")
    }

    @available(iOS 10.0, *)
    func tokenRefreshNotification(notification: UNUserNotificationCenter) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
            let deviceFCMToken: String = refreshedToken
            NSUserDefaults.standardUserDefaults().setObject(deviceFCMToken, forKey: "FCMToken")
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isFCMTokenAvailable")
             //UIApplication.sharedApplication().registerForRemoteNotifications()
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }
    func connectToFcm()
    {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil)
            {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }


extension AppDelegate : FIRMessagingDelegate
{
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage)
    {

        print("%@", remoteMessage.appData)
    }
}

最佳答案

由于您在另一个线程的评论部分要求我,我发布了这个工作代码集,其配置与您提到的相同:

import UserNotifications

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

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

        //############## FIREBASE ##################

        registerForPushNotifications(application)
        FIRApp.configure()
        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter
            .defaultCenter()
            .addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotification),
                         name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        //############ FIREBASE END ################  

        return true
    }


    //MARK: - FIREBASE START

    //######################################## FIREBASE START ###########################################

    func registerForPushNotifications(application: UIApplication) {

        if #available(iOS 10.0, *){
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
                if (granted)
                {
                    UIApplication.sharedApplication().registerForRemoteNotifications()
                }
                else{
                    //Do stuff if unsuccessful...
                }
            })
        }

        else{ //If user is not on iOS 10 use the old methods we've been using
            let notificationSettings = UIUserNotificationSettings(
                forTypes: [.Badge, .Sound, .Alert], categories: nil)
            application.registerUserNotificationSettings(notificationSettings)
        }
    }



    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != .None {
            application.registerForRemoteNotifications()
        }
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
        print("Device Token:", tokenString)
        print("Firebase Token:",FIRInstanceID.instanceID().token())
    }

    // [START receive_message]


    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        //Handle the notification
        //Use this place to handle
    }


    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
        //Handle the notification
        //Use this place to handle the notification
        print(response)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        print(userInfo)
    }

    // [END receive_message]

    // [START refresh_token]
    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()
    }

    // [END refresh_token]

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        //FBSDKAppEvents.activateApp()
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        //FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
    // [END disconnect_from_fcm]


    //###################################### FIREBASE ##########################################
    //######################################## END #############################################
}

负载格式:

[aps: {
    alert =     {
        body = "Some message.";
        title = "Some title";
     };
     category = " ";
 }, Name: ios, gcm.message_id: 0:1474608925388897%17bce75117bc5555]

关于ios - swift 2.3 中的 Xcode 8.1 推送通知与 firebase 集成没有得到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198651/

相关文章:

android - com.google.firebase.database.DatabaseException : Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance

javascript - 在 Firebase 中断期间,有一种方法可以通过运行本地代码来模拟这种情况

ios - 为整个应用更改 UITableViewCell 的背景 View

swift - View 旋转时播放有节奏的声音

swift - 异步中的 ActivityIndi​​cator - Swift

swift - AV 视频 URL 在内存中保留多长时间?

firebase - Flutter 中使用 firebase 身份验证进行电子邮件 OTP 验证

ios - Swift 中开关盒的穷举条件

javascript - 在 iOS 移动浏览器中请求位置权限弹出窗口

ios - UIStackView 零高度虽然我有内容