I am completely new to GCM integration with iOS i have an GCMSENDERID all i want to get registration token with this sender id.The function is also not getting called.let me know what mistake i have done or please give me some examples to sort it out.
#import "AppDelegate.h"
static NSString *const INSTANCE_ID_REGISTRATION_NOTIF_KEY = #"instance-id-token";
static NSString *const GCM_SENDER_ID = #"19398749911";
#interface AppDelegate ()
{
}
#property (nonatomic, strong) NSDictionary *registrationOptions;
#property (nonatomic, strong) GGLInstanceIDTokenHandler registrationHandler;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIUserNotificationType allNotificationTypes=(UIUserNotificationTypeSound|UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:settings];
[[UIApplication sharedApplication]registerForRemoteNotifications];
self.registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
//I do get the token, and I can store it
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:registrationToken forKey:INSTANCE_ID_REGISTRATION_NOTIF_KEY];
NSLog(#"Registration Token: %#", registrationToken);
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Start the GGLInstanceID shared instance with the default config and request a registration
// token to enable reception of notifications
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
self.registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#NO};//I tried both YES and NO value
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
- (void)onTokenRefresh {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(#"The GCM registration token needs to be changed.");
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// 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
// ...
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// 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
// ...
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Connect to the GCM server to receive non-APNS notifications
[[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
if (error) {
NSLog(#"Could not connect to GCM: %#", error.localizedDescription);
} else {
NSLog(#"Connected to GCM");
// ...
}
}];
}
Related
I have a problem which I've been unable to resolve. My knowledge of iOS/Xcode is limited, please forgive me.
I am trying to subscribe to an FCM topic for an iOS app using xcode/Objective C but when loading the App, it is not subscribing to the topic, in the debugger it doesn't even look like it is trying.
If I move the [[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
line to just below
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
(and above return YES;) then at least I get this error message indicating that it is at least trying.
2018-01-04 04:00:18.723760+0000 App[1049:1251125] [Firebase/Messaging][I-FCM002010] Cannot subscribe to topic: /topics/channel with token: (null)
So following the suggestion here (and a number of other places), I have tried to move it out into didRegisterUserNotificationSettings but it doesn't seem to be doing anything at all and there is no trace of it in the debugger.
This is my full AppDelegate.m code
//
// AppDelegate.m
//
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import <Firebase/Firebase.h>
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <FirebaseInstanceID/FirebaseInstanceID.h>
#import <AFNetworking/AFNetworking.h>
#import Firebase;
#interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupNetworkReachability];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error)
{
}];
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
//[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
return YES;
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UNNotificationSettings *)notificationSettings
{
[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
NSLog(#"Topic Registered");
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
#pragma mark - Public Methods
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (void)setupNetworkReachability
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN)
self.isNetworkAvailable = YES;
else
self.isNetworkAvailable = NO;
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
#pragma mark - FIRMessagingDelegate Methods
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(#"%#", notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}
#end
Would appreciate any help. Thank you.
Just to update, the App already receives message directly from FCM console, so that part works OK, it is just the topic subscription that is failing.
1: You should call [FIRApp configure]; before [FIRMessaging messaging].delegate = self;
2: As you post full code of your AppDelegate.m file. So it is missing the below method to update/send token to Firebase. You will receive a TOKEN with in this UIApplication's delegate method and you have to set it for Firebase (Just put this method in your AppDelegate.m file)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *strDevicetoken = [[NSString alloc]initWithFormat:#"%#",[[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] stringByReplacingOccurrencesOfString:#" " withString:#""]];
NSLog(#"Device Token = %#",strDevicetoken);
[FIRMessaging messaging].APNSToken = deviceToken;
//NSString *fcmToken = [FIRMessaging messaging].FCMToken;
//NSLog(#"FCM registration token: %#", fcmToken);
}
Now you have successfully set APNS Token at Firebase and you can now subscribe to your desired topic at Firebase
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
[FIRMessaging messaging].remoteMessageDelegate = self;
[[UIApplication sharedApplication] registerForRemoteNotifications];
[FIRApp configure];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFcm];
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Print message ID.
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Print message ID.
NSLog(#"message 2");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"%#", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSLog(#"message 3");
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"full data : %#", userInfo);
completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
completionHandler();
}
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(#"applicationReceivedRemoteMessage : %#", remoteMessage.appData);
}
- (void)tokenRefreshNotification:(NSNotification *)notification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(#"InstanceID token: %#", refreshedToken);
if(!(refreshedToken== nil)){
[defaults setValue:refreshedToken forKey:#"FcmToken"];
}
[self connectToFcm];
}
- (void)connectToFcm {
if (![[FIRInstanceID instanceID] token]) {
return;
}
[[FIRMessaging messaging] disconnect];
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications: %#", error);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APNs token retrieved: %#", deviceToken);
}
enter code here
When app is in the background mode, message not coming. When app is running foreground mode message shows in applicationReceivedRemoteMessage function. I need to run some code when message comes when background mode. Can anyone give me the solution for get the notifications works in background mode.
FIRMessaging connection won’t be allowed to live when in background it
is prudent to close the connection.
Please find here reference for the same: disconnect()
FirebaseMessaging Framework Reference
Simple Logic About Chat Applications: Socket Connection
Generally, Chat applications connects with other nodes (devices) using socket connection to transmit real-time information between nodes. Socket connections are disconnected, when apps goes into background.
FirebaseMessaging works on same logic and hence is won't work in background.
To handle message transmission in background mode, use power of PushNotification.
Also mark your code: You are disconnecting FIRMessaging when application goes into background. And you've done this, because the same is instructed in FIRMessaging guidelines.
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
As an alternate solution of your problem: You may have analyzed Whatapp or Facebook Messagner app. They use push notification to alert user for messages, when app goes into background. You should do the same.
App A is pushing a notification to App B like so:
NSDictionary *data = #{
#"alert" : #"Purchase Successful! 1 Remove Ads",
#"badge" : #"Increment",
#"sounds" : #"Bell.caf",
};
PFPush *push = [[PFPush alloc] init];
[push setChannels:#[ #"Mets" ]];
[push setData:data];
[push sendPushInBackground];
App B Receives the push notification like so:
//
// ParseStarterProjectAppDelegate.m
//
// Copyright 2011-present Parse Inc. All rights reserved.
//
#import <Parse/Parse.h>
// If you want to use any of the UI components, uncomment this line
// #import <ParseUI/ParseUI.h>
// If you are using Facebook, uncomment this line
// #import <ParseFacebookUtils/PFFacebookUtils.h>
// If you want to use Crash Reporting - uncomment this line
// #import <ParseCrashReporting/ParseCrashReporting.h>
#import "ParseStarterProjectAppDelegate.h"
#import "ParseStarterProjectViewController.h"
#implementation ParseStarterProjectAppDelegate
#pragma mark -
#pragma mark UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Enable storing and querying data from Local Datastore. Remove this line if you don't want to
// use Local Datastore features or want to use cachePolicy.
[Parse enableLocalDatastore];
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// [ParseCrashReporting enable];
//
// Uncomment and fill in with your Parse credentials:
[Parse setApplicationId:#"APPIDHERE" clientKey:#"CLIENTKEYHERE"];
//
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// [PFFacebookUtils initializeFacebook];
// ****************************************************************************
[PFUser enableAutomaticUser];
PFACL *defaultACL = [PFACL ACL];
// If you would like all objects to be private by default, remove this line.
[defaultACL setPublicReadAccess:YES];
[PFACL setDefaultACL:defaultACL withAccessForCurrentUser:YES];
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
if (application.applicationState != UIApplicationStateBackground) {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
BOOL preBackgroundPush = ![application respondsToSelector:#selector(backgroundRefreshStatus)];
BOOL oldPushHandlerOnly = ![self respondsToSelector:#selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)];
BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
[PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
}
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
} else
#endif
{
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound)];
}
return YES;
}
#pragma mark Push Notifications
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
[currentInstallation saveInBackground];
[PFPush subscribeToChannelInBackground:#"Mets" block:^(BOOL succeeded, NSError *error) {
if (succeeded) {
NSLog(#"ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
} else {
NSLog(#"ParseStarterProject failed to subscribe to push notifications on the broadcast channel.");
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
if (error.code == 3010) {
NSLog(#"Push notifications are not supported in the iOS Simulator.");
} else {
// show some alert or otherwise handle the failure to register.
NSLog(#"application:didFailToRegisterForRemoteNotificationsWithError: %#", error);
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
if (application.applicationState == UIApplicationStateInactive) {
[PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// if (application.applicationState == UIApplicationStateInactive) {
// [PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
// }
//}
#pragma mark Facebook SDK Integration
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
//- (BOOL)application:(UIApplication *)application
// openURL:(NSURL *)url
// sourceApplication:(NSString *)sourceApplication
// annotation:(id)annotation {
// return [PFFacebookUtils handleOpenURL:url];
//}
#end
How come I don't hear any sounds go off when App B receive's the push notification? No sound is played when the app is closed and the banner notification appears (which I'd like a sound), no sound is played when the app is open and the notification appears (just a vibrate, that's odd). Why is that and how do I fix it?
Do it like this:
NSDictionary *data = #{
#"alert" : #"you daily milk temp",
#"badge" : #"Increment",
#"sound" : #"super.caf"
};
PFPush *pusher = [[PFPush alloc] init];
[pusher setChannels:#[ #"deviceTemperatureReading" ]];
[pusher setData:data];
[pusher sendPushInBackground];
"super.caf" is a sound file
I followed this tutorial https://developers.google.com/cloud-messaging/ios/client to implement Google Cloud Messaging on my iOS application. I use google app engine as server side and the java library for GCM to send messages and it works perfectly for my Android application. However my iOS application does not receive messages from it.
I don't understand why because I do get the registration token and send it to my server side. I don't get any error log. Here is my AppDelegate.m code:
#import "AppDelegate.h"
#interface AppDelegate ()
#property (nonatomic, strong) NSDictionary *registrationOptions;
#property (nonatomic, strong) GGLInstanceIDTokenHandler registrationHandler;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//-- Start the GCMService
[[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
else
{
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
self.registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
//I do get the token, and I can store it
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:registrationToken forKey:CLE_TOKENGCM];
NSLog(#"Registration Token: %#", registrationToken);
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Start the GGLInstanceID shared instance with the default config and request a registration
// token to enable reception of notifications
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
self.registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#NO};//I tried both YES and NO value
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
- (void)onTokenRefresh {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(#"The GCM registration token needs to be changed.");
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:self.registrationOptions
handler:self.registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// 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
// ...
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);//This log never prints so the method is never called
// 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
// ...
}
#end
Thanks to ztan comment and to the Google GCM sample, I found out what was wrong: I had to implement applicationDidBecomeActive: like this:
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Connect to the GCM server to receive non-APNS notifications
[[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
if (error) {
NSLog(#"Could not connect to GCM: %#", error.localizedDescription);
} else {
NSLog(#"Connected to GCM");
// ...
}
}];
}
Hi I am a beginner in iOS. In my project I want to get GCM notifications for that I have written some code but it shows exception and my code is as following :
#import "AppDelegate.h"
#import <Google/CloudMessaging.h>
#import "GGLInstanceID.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound |
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
_registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
weakSelf.registrationToken = registrationToken;
NSLog(#"Registration Token: %#", registrationToken);
NSDictionary *userInfo = #{#"registrationToken":registrationToken};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
NSDictionary *userInfo = #{#"error":error.localizedDescription};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
_registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#YES};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
}
But it's shows Exception like
unresolved identifier "_registrationHandler" and "weakSelf" in
didFinishLaunchingWithOptions method and it exception in
didRegisterForRemoteNotificationsWithDeviceToken method like
unresolved identifier "_registrationOptions".
Please help me someone
Here I've refactored your code and it should work now.
static NSString *const INSTANCE_ID_REGISTRATION_NOTIF_KEY = #"instance-id-token";
static NSString *const GCM_SENDER_ID = #"<your sender id>"; // #"123456"
#interface AppDelegate ()
#property (nonatomic, strong, readwrite) GGLInstanceIDTokenHandler registrationHandler;
#property (nonatomic, strong, readwrite) NSString *registrationToken;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound |
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
NSDictionary *registrationOptions = #{
kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#YES
};
__weak typeof(self) weakSelf = self;
GGLInstanceIDTokenHandler handler = ^(NSString *registrationToken, NSError *error){
typeof(weakSelf) strongSelf = weakSelf;
NSDictionary *userInfo;
if (registrationToken != nil) {
strongSelf.registrationToken = registrationToken;
NSLog(#"Registration Token: %#", registrationToken);
userInfo = #{ #"registrationToken" : registrationToken };
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
userInfo = #{ #"error" : error.localizedDescription };
}
[[NSNotificationCenter defaultCenter] postNotificationName:INSTANCE_ID_REGISTRATION_NOTIF_KEY
object:nil
userInfo:userInfo];
};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:registrationOptions
handler:handler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
}
#end
PS: As #Epaga commented above you should really try to start off with a simple obj-c tutorial because your compiler issues were very trivial.