I am trying to register for push notifications in my iOS app. But it is calling neither the didRegisterForRemoteNotificationsWithDeviceToken nor didFailToRegisterForRemoteNotificationsWithError callback methods. I have revoked and regenerated the provisioning profile for the app.
I am using iOS8 and I have enabled the following background modes in my Info.plist
App registers for location updates
App downloads content in response to push notifications
App downloads content from the network
The code is:
-(void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Failed to register for push");
}
-(void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"did succeed in register for push");
// Get the device token string
const char* data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[self respondToEventNotification:userInfo];
}
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[self respondToEventNotification:userInfo];
}
Have you register your app with didFinishLaunchingWithOptions method for iOS8 like,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
You have to consider registration process of Push Notification in iOS8.
May this help you.
Related
I'm looking at the PHP code here:
https://gist.github.com/valfer/18e1052bd4b160fed86e6cbb426bb9fc
It looks good. I'd love to use it. But I'm confused about this:
* #param $token the token of the device
So I need the device token? For PHP code that is going to live on a server? How do I get the device token?
when iOS application is started, it registers itself for Apple Push Notifications by using the following code in your AppDelegate's didFinishLaunchingWithOptions.
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
}
and then following delegate methods may be called based on success or failure
-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSString* strdeviceToken = [[NSString alloc]init];
strdeviceToken=[self stringWithDeviceToken:deviceToken];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:strdeviceToken forKey:PREF_DEVICE_TOKEN];
[prefs synchronize];
NSLog(#"My token is===========> : %#",strdeviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
// NSLog(#"Failed to get token, error: %#", error);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"" forKey:PREF_DEVICE_TOKEN];
[prefs synchronize];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (application.applicationState == UIApplicationStateActive) {
// [self showToastMessage:#"Active"];
}
else if (application.applicationState == UIApplicationStateBackground) {
// [self showToastMessage:#"Background"];
}
else if (application.applicationState == UIApplicationStateInactive) {
// [self showToastMessage:#"Inactive"];
}
// [self handleIncomingNotification:userInfo delay:0.0];
}
All the above logic should be handled in AppDelegate class of your project. Then you can make some API call in your PHP code to be called from iOS and send this device token on your server and save it for future use.
On lower versions of IOS everything works fine, my code for push notifications:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)])
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
}
else
{
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
application.applicationIconBadgeNumber = 0;
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
//register to receive notifications
[application registerForRemoteNotifications];
}
//for sielent notifications
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
}
#endif
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
}
1) when running for the first time push notification popup asking for permission is not being called even when i re-call it using [[UIApplication sharedApplication] registerForRemoteNotifications]; the popup is not showing.
Make sure that Push Notifications are configured for your App ID.
If not, the device will ignore any push related methods.
I have implemented push notifications in my iOS8 app. I am trying to play an audio file once the notification is received.
The code is playing the audio when the app is in the foreground, but when the app is in the background, nothing happens.
I have tried regenerating the certificates and provisioning profiles. And I have made sure that the app is running in the background, i.e. the user has not swiped up to remove it. In Background modes, I have enabled Remote Notifications, Background Fetch and Audio & Airplay.
I have added code snippets from my AppDelegate.m file:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// More code here ---------------------------------------------------
if (launchOptions) {
NSDictionary *userInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
if (apsInfo) { //apsInfo is not nil
[self performSelector:#selector(playCarAlarmAudio)
withObject:nil
afterDelay:1];
}
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge
|UIUserNotificationTypeSound
|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
// More code here ---------------------------------------------------
}
The delegate methods to handle push notifications:
-(void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Failed to register for push");
}
-(void) application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[self respondToEventNotification:userInfo];
}
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// [self respondToEventNotification:userInfo];
[self playAlarmAudio];
}
-(void) respondToEventNotification : (NSDictionary *) userInfo {
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
[localNotification setSoundName:#"alarm.mp3"];
[localNotification setFireDate:[NSDate date]];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
else if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
[self playAlarmAudio];
}
}
And to play the Alarm:
-(void) playAlarmAudio {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"alarm" ofType:#"mp3"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
self.audioPlayer.numberOfLoops = 1;
[self.audioPlayer play];
}
According to the following Apple documentation, the notification sound to be played is specified inside the notification payload dictionary (https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html):
The Notification Payload
Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)
For each notification, compose a JSON dictionary object (as defined by RFC 4627). This dictionary must contain another dictionary identified by the key aps. The aps dictionary can contain one or more properties that specify the following user notification types:
An alert message to display to the user
A number to badge the app icon with
A sound to play
i have a code that works in iOS 7, i receive all the Push Notifications.
When implementing the new iOS 8 Push Notification using Parse.com, i can't make it work.
Here is the code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Register for push notifications
[Parse setApplicationId:#"XXXX" clientKey:#"XXX"]; // REMOVED IDS FOR SECURITY REAS
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIMutableUserNotificationAction *viewAction = [[UIMutableUserNotificationAction alloc] init];
viewAction.identifier = #"medphone-view";
viewAction.title = #"Ver";
viewAction.activationMode = UIUserNotificationActivationModeForeground;
viewAction.destructive = NO;
UIMutableUserNotificationAction *dismissAction = [[UIMutableUserNotificationAction alloc] init];
dismissAction.identifier = #"medphone-dismiss";
dismissAction.title = #"Excluir";
dismissAction.activationMode = UIUserNotificationActivationModeBackground;
dismissAction.destructive = YES;
UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
category.identifier = #"medphone";
[category setActions:[NSArray arrayWithObjects:viewAction, dismissAction, nil] forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObjects:category, nil];
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[application registerUserNotificationSettings:mySettings];
[application registerForRemoteNotifications];
} else {
[application registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
if (launchOptions) { //launchOptions is not nil
NSDictionary *userInfo = [launchOptions valueForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"];
NSLog(#"Push info %#", userInfo);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
if (apsInfo) { //apsInfo is not nil
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setValue:userInfo forKey:#"PUSHDATA"];
[prefs setBool:YES forKey:#"PUSH"];
[prefs synchronize];
NSLog(#"entrou no UIApplicationLaunchOptionsRemoteNotificationKey %#", apsInfo);
}
}
return YES;
}
And these other methods:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
currentInstallation.channels = #[#"global"];
[currentInstallation saveInBackground];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushNotification" object:userInfo];
NSLog(#"entrou no didReceiveRemoteNotification %#", userInfo);
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//register to receive notifications
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler {
NSLog(#"entrou no UIApplicationLaunchOptionsRemoteNotificationKey %#", userInfo);
//handle the actions
if ([identifier isEqualToString:#"medphone-view"]) {
NSLog(#"ver");
} else if ([identifier isEqualToString:#"medphone-dismiss"]) {
NSLog(#"dismmis");
}
completionHandler();
}
#endif
Is there anything i`m doing wrong? The payload is correct, bacause its working on iOS 7. And the category is set.
Please me let me know!
The code for iOS 8 has Changed:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{ [[UIApplication sharedApplication] registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeSound |
UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)];
}
I have an app that will set an alarm for the user. The alarm is a basic UILocalNotification with a sound file that is 12 seconds long. The sound plays on the device but it does not go away when the use dismisses the notification. I got it to stop playing sound on the simulator by using this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
}
return YES;
}
Any help would be great.
Thank you
I put this on my AppDelegate and it works.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
Hope it help.