Google Cloud Messaging in iOS - ios

Hi i want to implement GCM in iOS and i have my SenderID but i dont know where i have to implement SenderID.This is my entire code for GCM integration.i need TOKEN value.so please guide me to get it done.
Appdelegate :
#import "AppDelegate.h"
#interface AppDelegate ()
{
NSDictionary *RegistrationOptions;
NSString *GcmSenderID;
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];
return YES;
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
// Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
GGLInstanceIDConfig *instanceIDConfig = [GGLInstanceIDConfig defaultConfig];
instanceIDConfig.delegate = self;
// Start the GGLInstanceID shared instance with the that config and request a registration
// token to enable reception of notifications
[[GGLInstanceID sharedInstance] startWithConfig:instanceIDConfig];
RegistrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#YES};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GcmSenderID
scope:kGGLInstanceIDScopeGCM
options:RegistrationOptions
handler:registrationHandler];
}
- (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:GcmSenderID
scope:kGGLInstanceIDScopeGCM
options:RegistrationOptions
handler:registrationHandler];
}

Its pretty late answer.But it will help someone in future.
You just have to upload apns certificate (developer and production) and get the gcm config file and add it to your project (drag and drop to your project).
The following code which you should call in the didFinishLaunchingWithOptions will automatically fetch the _gcmSenderID from the config file.
_gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];
Here is a sample quick start project for you to start with.(both swift and objective-C).Everything is well explained in this sample app.Let me know if you have any doubts.

Related

Implementing Pusher APNs Notification

following this promising tutorial from nickjf89 I try to implement Push Notification in a vanilla Cordova project.
Until now, I'm able to get communication with the socket, when I push data from the Pusher console, all works, so I exclude any misconfiguration on Pusher API.
The "only" thing which fail is the actual Push Notification.
Looking at the Push Notification console, I see my request arriving on my cordova channel.
But in the xCode console, I don't see the expected log from NSLog(#"Received remote notification: %#", userInfo);
I suspect I got an issue with my AppDelegate.m which is below.
#import "AppDelegate.h"
#import "MainViewController.h"
#import UserNotifications;
#import <PusherSwift/PusherSwift-Swift.h>
#interface AppDelegate ()
#property (nonatomic, retain, readwrite) Pusher *pusher;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.viewController = [[MainViewController alloc] init];
self.pusher = [[Pusher alloc] initWithKey:#"here_i_put_my_pusher_app_key"];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorisation.
}];
[application registerForRemoteNotifications];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Registered for remote notifications; received device token");
[[[self pusher] nativePusher] registerWithDeviceToken:deviceToken];
[[[self pusher] nativePusher] subscribeWithInterestName:#"cordova"];
NSLog(#"Seeems token stuff works");
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Received remote notification: %#", userInfo);
}
#end
Ok, one time again, the issue was between the chair and the keyboard...
I found the fix, it was related to the APNs certificate uploaded on Pusher and the my-app-name.entitlements where APS environment was set on production instead of development.
All fixed and functional, great new feature from Pusher!

google play game check for user is sign in or not

i have implemented google play games in my app for leaderboard.
my requirement is to display info Alert when user login first time in safari(redirect to safari automatically for login)
i have written this code
[GPGManager sharedInstance].statusDelegate = self;
BOOL isSignedIn = [[GPGManager sharedInstance] signInWithClientID:kGoogleClient silently:flag];
NSLOG(#“is signedin %d",[GPGManager sharedInstance].isSignedIn);
but every time [GPGManager sharedInstance].isSignedIn this variable returns false.
any one have any idea ??
You must configure the GGLContext shared instance. You can do this in many places in your app. Often the easiest place to configure this instance is in your app delegate's application:didFinishLaunchingWithOptions: method.
In your app delegate's .h file, declare that this class implements the GIDSignInDelegate protocol.
#import <Google/SignIn.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate, GIDSignInDelegate>
AppDelegate.h
In your app delegate's application:didFinishLaunchingWithOptions: method, configure the GGLContext shared instance and set the sign-in delegate.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSError* configureError;
[[GGLContext sharedInstance] configureWithError: &configureError];
NSAssert(!configureError, #"Error configuring Google services: %#", configureError);
[GIDSignIn sharedInstance].delegate = self;
return YES;
}
Implement the application:openURL:options: method of your app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary *)options {
return [[GIDSignIn sharedInstance] handleURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
In the app delegate, implement the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods:
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
// Perform any operations on signed in user here.
NSString *userId = user.userID; // For client-side use only!
NSString *idToken = user.authentication.idToken; // Safe to send to the server
NSString *fullName = user.profile.name;
NSString *givenName = user.profile.givenName;
NSString *familyName = user.profile.familyName;
NSString *email = user.profile.email;
// ...
}
- (void)signIn:(GIDSignIn *)signIn
didDisconnectWithUser:(GIDGoogleUser *)user
withError:(NSError *)error {
// Perform any operations when the user disconnects from app here.
// ...
}

unable to register (com.google.iid error 1005.)

I'm attempting to integrate GCM into our iOS app.
I've followed the instructions to update our project for GCM to no avail.
Everything I try to register I get:
Registration to GCM failed with error: The operation couldn’t be completed. (com.google.iid error 1005.)
Which GLLInstance.h say:
/// Should call `startWithConfig:` before requesting token.
kGGLInstanceIDOperationErrorCodeInvalidStart = 1005,
I am calling :
[[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];
before registering for notifications...
There aren't any obvious errors from GCM
This IS on a device...
(just trying to eliminate the obvious)
What next steps should I try?
As usual as soon as I post a question to SO, the answer leaps out at me.
The routine:
[[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];
which I knew I was calling in:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
right before
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
was needed in two locations... I missed that.
Once I added it just before the call:
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];
in:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
everything started working.
Delightful...

Sinch delegate method "shouldSendPushNotification" not being called

I'm playing with Sinch and have some problems with Push notifications.
Firstly I can use Sinch to send and receive messages (two devices
with two different Sinch IDs). So that means the Sinch Client is
correctly configured.
Secondly I can confirm the push notification are correctly set on
both of the devices, because I can send push notifications to them on
Parse.com. They all have valid push notification tokens.
Then in my app, I found that the Sinch delegate method: shouldSendPushNotification is not called when the receiver side is not "online".
I did a search on SO and found there's a similar question (Sinch, message shouldSendPushNotification not being called) which suggested to check the messageSent call back.
Therefore I tried the following in the receiver side:
put the app into background by pressing home
force quit the app (double click home, remove the app from background)
enable flight mode
After that when a message sent, I can see:
- (void)messageSent:(id<SINMessage>)message recipientId:(NSString *)recipientId
is being invoked in the sender's side and the recipientId is the same as the destination device's. But the shouldSendPushNotification method is never being called as stated in Sinch's documentation.
Since this shouldSendPushNotification method is not invoked, there will not be any push notifications being sent out to the destination device.
I've been working on this problem for several days, and very keen to know the solution, any help is appreciated.
Test environment
two devices in iOS 8 beta 4 and one in iOS 7.1.2
build using XCode 6 beta 4
Code:
Setting up the Sinch messaging service in AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
// setup Parse
[Parse setApplicationId:#"xxxxx"
clientKey:#"xxxxx"];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
// use registerUserNotificationSettings
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories: UIUserNotificationActionContextDefault]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
// use registerForRemoteNotifications
// Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
#else
// use registerForRemoteNotifications
// Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
#endif
// app response from the notifications while in background
NSDictionary* remotePush = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remotePush) {
// Extract the Sinch-specific payload from the Apple Remote Push Notification
NSString* payload = [remotePush objectForKey:#"SIN"];
// Get previously initiated Sinch client
id<SINNotificationResult> result = [_client relayRemotePushNotificationPayload:payload];
if (result.isMessage) {
// Present alert notifying
NSString *messageId = [[result messageResult] messageId];
NSLog(#"Received messageid: %#", messageId);
} else if (!result.isValid) {
// Handle error
}
NSLog(#"Received Payload: %#", payload);
}
return YES;
}
- (void)initSinchClientWithUserId:(NSString *)userId {
if (!_client) {
_client = [Sinch clientWithApplicationKey:#"xxxx"
applicationSecret:#"xxxx"
environmentHost:#"sandbox.sinch.com"
userId:userId];
_client.delegate = self;
[_client setSupportMessaging:YES];
[_client setSupportPushNotifications:YES];
[_client setSupportActiveConnectionInBackground:NO];
[_client start];
[_client startListeningOnActiveConnection];
}
}
And this line is called as expected when the app starts
- (void)clientDidStart:(id<SINClient>)client {
NSLog(#"Sinch client started successfully (version: %#)", [Sinch version]);
}
Inside the app's MessageSendingViewController
- (id<SINClient>)client {
return [(AppDelegate *)[[UIApplication sharedApplication] delegate] client];
}
-(void)viewDidLoad {
...
[self.client messageClient].delegate = self;
...
}
Are you registering "push data" (e.g. your APN token) via the method -[SINClient registerPushNotificationData:]?
Try something like:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[_client registerPushNotificationData:deviceToken];
}
(There is also more details here on http://www.sinch.com/docs/ios/user-guide/#pushnotifications)
Problem solved with some help from the Sinch.
First make sure that client is not nil (0x0) when the delegate method registerPushNotificationData:deviceToken is being called.
In my case, I need to manually register notification settings again after starting the Sinch client.
Once the client is started and notification settings are registered, the shouldSendPushNotification method should be called without any problems.

Device Token incorrect with Urban Airship?

I'm trying to implement push notifications in my app. So, for testing, I built up a new app and did all the necessary steps (I hope...). I added to my project the following:
-AirshipConfig.plist
-libUAirship-1.1.4.a
-UAGLobal.
-UAirship.h
-UAObservable.h
-UAPush.h
and all the frameworks listed on their website.
My AppDelegate.m is:
#import "AppDelegate.h"
#import "UAirship.h"
#import "UAPush.h"
#implementation AppDelegate
#synthesize window = _window;
-(void)setupPushWithOptions:(NSDictionary *)launchOptions {
//URBAN AIRSHIP PUSH NOTIFICATION CONFIGURATION
//Init Airship launch options
NSMutableDictionary *airshipConfigOptions = [[NSMutableDictionary alloc] init];
//[airshipConfigOptions setValue:#"5QQmJyTMRZWks0nbx-9pHQ" forKey:#"DEVELOPMENT_APP_KEY"];
//[airshipConfigOptions setValue:#"OMuzzHdCQOCnrOtfiWox9Q"
forKey:#"DEVELOPMENT_APP_SECRET"];
[airshipConfigOptions setValue:#"xrUoy0B1RdyjZqZXEuwIsg" forKey:#"PRODUCTION_APP_KEY"];
[airshipConfigOptions setValue:#"qiRlUvoaSHGNeXxw9pj71w" forKey:#"PRODUCTION_APP_SECRET"];
#ifdef DEBUG
[airshipConfigOptions setValue:#"NO" forKey:#"APP_STORE_OR_AD_HOC_BUILD"];
#else
[airshipConfigOptions setValue:#"YES" forKey:#"APP_STORE_OR_AD_HOC_BUILD"];
#endif
NSMutableDictionary *takeOffOptions = [[NSMutableDictionary alloc] init];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];
[takeOffOptions setValue:airshipConfigOptions
forKey:UAirshipTakeOffOptionsAirshipConfigKey];
// Create Airship singleton that's used to talk to Urban Airship servers.
// Please replace these with your info from http://go.urbanairship.com
[UAirship takeOff:takeOffOptions];
[[UAPush shared] resetBadge];//zero badge on startup
[[UAPush shared]
registerForRemoteNotificationTypes:UIRemoteNotificationTypeNewsstandContentAvailability|UIRemoteNotificationTypeAlert]; // register for Newsstand and Alerts
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
//Init Airship launch options
NSMutableDictionary *takeOffOptions = [[NSMutableDictionary alloc] init];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];
// Create Airship singleton that's used to talk to Urban Airship servers.
// Please populate AirshipConfig.plist with your info from http://go.urbanairship.com
[UAirship takeOff:takeOffOptions];
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)];
// Override point for customization after application launch.
[self setupPushWithOptions:launchOptions];
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
UALOG(#"APN device token: %#", deviceToken);
NSLog(#"%#", deviceToken);
// Updates the device token and registers the token with UA
[[UAirship shared] registerDeviceToken:deviceToken];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
-(void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Failing in APNS registration: %#",error);
}
#end
In this way I get the Error Apple Push service rejected device token
But I also figured out that my device token could be retrieved not correctly. Following a UA member staff suggestion I downloaded from the Appstore the App Wide Angle, and I launched it witht my iPhone connected and with the Xcode console open. So I can see that my device token is another one...Where could it be the problem?
You shouldn't hardcode your variabels into Urban Airship like this.
Create AirshipConfig.plist The library uses a .plist configuration
file named AirshipConfig.plist to manage your production and
development application profiles.
Create 2 applications within your Urban Airship account - one for
development & another for production. Ex. Name_of_your_app_dev
Name_of_your_app_prod Create an AirshipConfig.plist file Set the
following values to the ones in your applications

Resources