1
votes

Using GCM for push notification in iOS. Everything is set up nicely. I'm getting registrationToken value & also subscribeToTopic successfully. Connected to GCM. didRegisterForRemoteNotificationsWithDeviceToken method also called. But not getting push notification. didReceiveRemoteNotification method never called. On my android app I'm getting the push notification without any problem. But in iOS notification never received. Here is the source code:

    class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate{
var gcmSenderID: String?
var registrationToken: String?
let registrationKey = "onRegistrationCompleted"
let messageKey = "onMessageReceived"
var registrationOptions = [String: AnyObject]()
var connectedToGCM = false
let subscriptionTopic = "/topics/global"
var subscribedToTopic = false

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

    var configureError:NSError?

    GGLContext.sharedInstance().configureWithError(&configureError)

    gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID

    if application.respondsToSelector("registerUserNotificationSettings:") {

        let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
        let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()

    } else {
        // Register for Push Notifications before iOS 8
        application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
    }
    let gcmConfig = GCMConfig.defaultConfig()
    gcmConfig.receiverDelegate = self
    GCMService.sharedInstance().startWithConfig(gcmConfig)

    return true

}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    print("remote notification")
    GCMService.sharedInstance().appDidReceiveMessage(userInfo);

}
func application( application: UIApplication,
    didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
    fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
        GCMService.sharedInstance().appDidReceiveMessage(userInfo);

   NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
            userInfo: userInfo)
        handler(UIBackgroundFetchResult.NoData);


}
func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
    deviceToken: NSData ) {

        let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
        instanceIDConfig.delegate = self

     GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
        registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
            kGGLInstanceIDAPNSServerTypeSandboxOption:true]

        GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
            scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
        // [END get_gcm_reg_token]
}
func onTokenRefresh() {
    // A rotation of the registration tokens is happening, so the app needs to request a new token.
    print("The GCM registration token needs to be changed.")
    GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
        scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
func registrationHandler(registrationToken: String!, error: NSError!) {
    if (registrationToken != nil) {

        self.registrationToken = registrationToken
        print("Registration Token: \(registrationToken)")
        self.subscribeToTopic()
        let userInfo = ["registrationToken": registrationToken]
        NSNotificationCenter.defaultCenter().postNotificationName(
            self.registrationKey, object: nil, userInfo: userInfo)
    } else {
        print("Registration to GCM failed with error: \(error.localizedDescription)")
        let userInfo = ["error": error.localizedDescription]
        NSNotificationCenter.defaultCenter().postNotificationName(
            self.registrationKey, object: nil, userInfo: userInfo)
    }
}
func subscribeToTopic() {

    // 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 {
                        print("Already subscribed to \(self.subscriptionTopic)")
                    } else {
                        print("Subscription failed: \(error.localizedDescription)");
                    }
                } else {
                    self.subscribedToTopic = true;
                    NSLog("Subscribed to \(self.subscriptionTopic)");
                }
        })
    }
}


func applicationDidBecomeActive(application: UIApplication) {
    print("applicationDidBecomeActive")
    self.globalPrice = CartLocalData.getTotalPrice()
     GCMService.sharedInstance().connectWithHandler({
        (NSError error) -> Void in
        if error != nil {
            print("Could not connect to GCM: \(error.localizedDescription)")

        } else {
            self.connectedToGCM = true
            self.subscribeToTopic()
            print("Connected to GCM")
            // ...
        }
    })

}

}

What am I doing wrong. Can anyone suggest??

1
do you have the right capabilities set up in the app target? and made the push provisions?bolnad
yes I have the push provision. do I need anything additional in app target??Linkon Sid
you need to turn it on in the capabilities section and when you build the app you need to have the push notification key/cert pair on your machine that lets you build itbolnad
possible duplicate SO ticket kindly refer to this linkMr.Rebot
for ur kind information that link doesnt solve my problemLinkon Sid

1 Answers

0
votes

you should have the option to turn on push from capabilities section. You also need to build separate key/cert pair in the apple member center and have those included on your machine. here is a screenshot from a new project i made.

capabilities section

It sounds like maybe one of the steps in the process might not be done.

Start over again and try to figure out what your missing. here is a ray wenderlich tutorial that walks you through the steps here

And the link to Apple developer site that talks about it in depth here