简体   繁体   English

未收到GCM推送通知

[英]GCM push notifications not received

In my project I have to get GCM push-notifications and I done everything perfect and also server sent to me registration token and GCM server connected perfectly but notifications are not coming in my device. 在我的项目中,我必须得到GCM推送通知,我完成了一切,并且服务器发送给我注册令牌和GCM服务器完美连接但通知不在我的设备中。

my xcode console showing like this: 我的xcode控制台显示如下:

2015-07-17 11:20:41.701 GCMSwift[1134:421304] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.
2015-07-17 11:20:41.718 GCMSwift[1134:421304] Attempted to configure [Identity, Analytics, AdMob, SignIn, AppInvite, CloudMessaging].
2015-07-17 11:20:41.719 GCMSwift[1134:421304] Successfully configured [CloudMessaging].
2015-07-17 11:20:41.720 GCMSwift[1134:421304] Failed to configure [].
2015-07-17 11:20:41.721 GCMSwift[1134:421304] Subspecs not present, so not configured [Identity, Analytics, AdMob, SignIn, AppInvite].
Registration Token: l3OcbsTm5nQ:APA91bGs6cUSE8GeJZcsW3pL6i-O4VIwDqifLFzfwnKjZDQy6bD0zlxiqAH-XfErDzmZka5q5o01YnN9a8roCfQnP0QGarpZk2dtt5ebL0GImkSCQYfqrrK1VCshT8Jo7MMYuEHvktUE
Connected to GCM
Already subscribed to /topics/global

And this is my code: 这是我的代码:

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate,GGLInstanceIDDelegate {

    var window: UIWindow?

    // GCM iVars.
    var registrationOptions = [String: AnyObject]()
    var gcmSenderID: String?

    var connectedToGCM = false
    var subscribedToTopic = false
    var registrationToken: String?

    let registrationKey = "onRegistrationCompleted"
    let messageKey = "onMessageReceived"
    let subscriptionTopic = "/topics/global"

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        /**************** GCM Google service. ***********************/
        // [START_EXCLUDE]
        // Configure the Google context: parses the GoogleService-Info.plist, and initializes
        // the services that have entries in the file
        var configureError:NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        if configureError != nil {
            println("Error configuring the Google context: \(configureError)")
        }
        gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID
        // [END_EXCLUDE]

        // Register for remote notifications
        var types: UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
        var settings: UIUserNotificationSettings =
        UIUserNotificationSettings( forTypes: types, categories: nil )
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()

        // [START start_gcm_service]
        GCMService.sharedInstance().startWithConfig(GCMConfig.defaultConfig())
        // [END start_gcm_service]

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        // Start the GGLInstanceID shared instance with the default config and request a registration token to enable reception of notifications
        GGLInstanceID.sharedInstance().startWithConfig(GGLInstanceIDConfig.defaultConfig())
        registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
            kGGLInstanceIDAPNSServerTypeSandboxOption:true]
        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    }

    // [START receive_apns_token_error]
    func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
        error: NSError ) {
            println("Registration for remote notification failed with error: \(error.localizedDescription)")
            // [END receive_apns_token_error]
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                registrationKey, object: nil, userInfo: userInfo)
    }


    func onTokenRefresh() {
        // A rotation of the registration tokens is happening, so the app needs to request a new token.
        println("The GCM registration token needs to be changed.")
        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
            scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
    }

    func registrationHandler(registrationToken: String!, error: NSError!){
        // registration handeler.
        if (registrationToken != nil) {
            self.registrationToken = registrationToken
            println("Registration Token: \(registrationToken)")
            self.subscribeToTopic()
            let userInfo = ["registrationToken": registrationToken]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        } else {
            println("Registration to GCM failed with error: \(error.localizedDescription)")
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        }
    }

    func subscribeToTopic() {
        // If the app has a registration token and is connected to GCM, proceed to subscribe to the
        // topic
        if(registrationToken != nil && connectedToGCM) {
            GCMPubSub.sharedInstance().subscribeWithToken(self.registrationToken, topic: subscriptionTopic,
                options: nil, handler: {(NSError error) -> Void in
                    if (error != nil) {
                        // Treat the "already subscribed" error more gently
                        if error.code == 3001 {
                            println("Already subscribed to \(self.subscriptionTopic)")
                        } else {
                            println("Subscription failed: \(error.localizedDescription)");
                        }
                    } else {
                        self.subscribedToTopic = true;
                        NSLog("Subscribed to \(self.subscriptionTopic)");
                    }
            })
        }
    }

    /******************** DID RECIEVE PUSH NOTIFICATION ************************/
    // [START ack_message_reception]
    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
            println("Notification received: \(userInfo)")
            // This works only if the app started the GCM service
            GCMService.sharedInstance().appDidReceiveMessage(userInfo);
            // Handle the received message
            // [START_EXCLUDE]
            NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                userInfo: userInfo)
            // [END_EXCLUDE]
    }

    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
        fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
            println("Notification received: \(userInfo)")
            // This works only if the app started the GCM service
            GCMService.sharedInstance().appDidReceiveMessage(userInfo);
            // Handle the received message
            // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
            // [START_EXCLUDE]
            NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
                userInfo: userInfo)
            handler(UIBackgroundFetchResult.NoData);
            // [END_EXCLUDE]
    }
    // [END ack_message_reception]


    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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        GCMService.sharedInstance().disconnect()
        // [START_EXCLUDE]
        self.connectedToGCM = false
        // [END_EXCLUDE]
        println("Stop executing app and whent into background!")
    }

    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.
        GCMService.sharedInstance().connectWithHandler({
            (NSError error) -> Void in
            if error != nil {
                println("Could not connect to GCM: \(error.localizedDescription)")
            } else {
                self.connectedToGCM = true
                println("Connected to GCM")
                // [START_EXCLUDE]
                self.subscribeToTopic()
                // [END_EXCLUDE]
            }
        })
    }

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

}

But notifications are not receiving to my device, do I have to do anything extra here? 但通知没有收到我的设备,我是否需要在这里做额外的事情? and did I forget to add anything? 我忘了添加任何东西吗? and I uploaded .p12 certificate and I have created APNs certificate perfectly why I did not get GCM notifications and "didReceiveRemoteNotification" method is not calling do I have to attach server API key or SenderId along with code what I written above. 我上传了.p12证书,我已经完全创建了APNs证书,为什么我没有得到GCM通知和“didReceiveRemoteNotification”方法没有调用我必须附上服务器API密钥或SenderId以及我上面写的代码。

If you see your console first line: 如果你看到你的控制台第一行:

2015-07-17 11:20:41.701 GCMSwift[1134:421304] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist

You need to enable the Required background modes . 您需要启用所需的后台模式 Follow the steps: 按照步骤:

  • In the Project Navigator click the project Project Navigator中单击该项目
  • In the Projects and Targets list click the target . 在“项目和目标”列表中,单击目标
  • Click Capabilities 单击功能
  • Expand and turn on Background Modes 展开并启用背景模式
  • Click Remote Notifications 单击“ 远程通知”

This will add the background mode support in your Info.plist. 这将在Info.plist中添加后台模式支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM