Push Notification Badges not Coming - iphone

I am using this coding for apple push notification, push notifications are coming but they are coming without any badges, any suggestion what is wrong with this code, that I am not getting badges. I already check the setting tab, and badges are on there.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken1 {
NSString *str = [NSString
stringWithFormat:#"%#",deviceToken1];
NSLog(#"%#",str);
self.deviceToken = [NSString stringWithFormat:#"%#",str];
NSLog(#"dev --- %#",self.deviceToken);
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#"<" withString:#""];
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#" " withString:#""];
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#">" withString:#""];
NSLog(#"dev --- %#",self.deviceToken);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: #"Error: %#", err];
NSLog(#"%#",str);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Received notification: %#", userInfo);
//[self addMessageFromRemoteNotification:userInfo];
NSString* alertValue = [[userInfo valueForKey:#"aps"] valueForKey:#"badge"];
NSLog(#"my message-- %#",alertValue);
int badgeValue= [alertValue intValue];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeValue];
}

There was a problem with my server side coding as I just find out that badge value has to be implicitly set as integer to get desired result.
As I'm getting null value in badge value.

I have faced this issue before , hope this helps
{"aps":{"alert":"dsfdsfsdfsdfsdfdfdfsdfsdf","badge":1,"sound":"a"}}
make sure there is no double quotation mark on badge value

Related

How to Get Device Token in didFinishLaunchingWithOptions

I am calling device token in my first viewcontroller. And I cant get result because Device token is null. Here below is my code in appdelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"Device Token ---%#", token);
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
When I am calling in Viewcontroller :
NSString *token= [[NSUserDefaults standardUserDefaults] objectForKey:#"DeviceToken"];
token is null.
NSString *device = [deviceToken description];
device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
device = [device stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"My device is: %#", device);
This worked perfectly for me in my device.
Refer to Kulss' answer in this SO Answer:
How can I convert my device token (NSData) into an NSString?
You should be parsing the bytes not the description.
First
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Add this in Application.h
try this one my friend....
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
#if !TARGET_IPHONE_SIMULATOR
// Prepare the Device Token for Registration (remove spaces and < >)
token = [[[[devToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"%#",token);
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
#endif
}
/**
* Failed to Register for Remote Notifications
*/
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"Error in registration. Error: %#", error);
#endif
}
Happy Coding!!!!
Add two methods didRegister and didFailToRegister, and confirm are u getting a call in didRegister or in didFailedToRegister.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(#"Device Token=> %#",deviceToken);
//Parse your device toke
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Error in registration. Error: %#", error.description);
}
and assure are u getting succesfully ur device token. Or u r failed to registerForRemote...
You can try this one
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*) deviceToken {
NSString *pushToken = [deviceToken description];
pushToken = [pushToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
[[NSUserDefaults standardUserDefaults] setObject:pushToken forKey:#"device_token_data"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
May be help you.
First register notification in then you will get toke in didRegisterRemoteNotification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
self.strdeviceToken=[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
self.strdeviceToken = [self.strdeviceToken stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
self.strdeviceToken=[self.strdeviceToken stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
}
You should check your provisioning profile. Also the App should be configured for push notification on developer portal.
Perform these steps for doing so.
Enable push notification for your Application Identifier on Developer portal.
regenerate the provisioning profile.
Download and install new provisioning profile.
Build and run.
It will work.
try this one..
after your transactions completed, you want token number in the view controller. so for that try to make or change root view controller again in appDelegate by the method like this in AppDelegate.m.
-(void)changeRootView
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
//Adding navigation controller to the main view.
[navigationController release];
navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
}
in this method
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
this statement is helped to call didRegisterForRemoteNotificationsWithDeviceToken again and you can store the token in some object like NSUserDefaults and you can use it in your viewController. It works for me. you can try this. Best luck.

Redirect UIAlertView Button Push Notifications

I have read many posts on this matter, but none of them really helps me out. It seems quite easy to do, but somehow I can't figure it out.
What am I trying to do here?
Well, I send a push notifications to my app. Everything works fine.
I can handle it when it is in the background, inactive or even when the app is not running.
But one other state - app in foreground - gives me a headache.
I have this code snippet which I'm using. All fine.
When the app is running in the foreground, the user gets the UIAlertview.
But how do I add an action to the view button?
This particular action I mean: when someone taps the view button he/she gets redirected to the url which has been passed through the push notification.
Just like I have used before in the code snippet (this part to be precise):
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
I hope this makes sense and someone can help me out. I'm lost at this one ... This is the entire code snippet which is relevant at this subject.
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
// We need the url that has been passed by the push notification
}
else {
// Do something
}
}
Just define your variable notifUrl in .h file so that you can access this in other methods of your class as well. Then store url in that variable and use that in alertview delegate method.
//Add this in .h file
NSString *notifUrl;
//Add this in .m file
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
//Define this variable in .h file so that you can access this in other methods as well
notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
[notifUrl retain]; // this is retain value of notifUrl so that you can use it later
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
NSLog(#"Received Push Url: %#", notifUrl);
[self Redirect:notifUrl];
}
else {
// Do something
}
}

Repeat alarm at particular time interval

Issue is, i put a date picker programmatically. In date picker i just used to display time from 1mins to 23 hours. User is supposed to set the time in the picker, and set up the notification.
Now,i get notification in background but only one time.I have to repeat time until timer will not stop.
I found too many links and source but not able to solve this issue
My Code:
In Appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
application.applicationIconBadgeNumber = 0;
//------ Handle launching from a notification-------
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
self.localNotification =[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (self.localNotification)
{
application.applicationIconBadgeNumber = self.localNotification.applicationIconBadgeNumber-1;
NSLog(#"badge number: %d", application.applicationIconBadgeNumber);
[self playSoundWithNotification:self.localNotification];
}
else
{
[[UIApplication sharedApplication]cancelAllLocalNotifications];
}
}
didenterinbackground:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(#"Application entered background state.");
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_main_queue(), ^{
while ([application backgroundTimeRemaining] > 1.0)
{
NSString *str_friend = #"Hello,";
if (str_friend)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif)
{
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(#"%# has a message for you.", nil), str_friend];
localNotif.alertAction = NSLocalizedString(#"Read Msg", nil);
localNotif.soundName = #"alarmsound.caf";
//localNotif.soundName =[NSString stringWithFormat:#"%#.mp3",str_Alarm];
localNotif.applicationIconBadgeNumber = 1;
[application presentLocalNotificationNow:localNotif];
NSLog(#"sound: %#, alertAction: %#, alerBody: %#",localNotif.soundName, localNotif.alertAction, localNotif.alertBody);
str_friend = nil;
break;
}
}
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}
-
(void)playSoundWithNotification:(UILocalNotification *)notification
{
notification.soundName=[NSString stringWithFormat:#"%#.mp3",str_Alarm];
NSLog(#"soundname: %#",notification.soundName);
}
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{
testDate=notif.fireDate;
NSLog(#"DATE IS: %#, %#",testDate, notif.fireDate);
// Handle the notificaton when the app is running
NSLog(#"Recieved Notification %#",notif);
[self playSoundWithNotification:notif];
[self _showAlert:[NSString stringWithFormat:#"%#",str_Motivation] withTitle:#"Daily Achiever"];
}
- (void) _showAlert:(NSString*)pushmessage withTitle:(NSString*)title
{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:pushmessage delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
if (alertView)
{
}
}
in myviewcontroller:
-(void)insert:(NSDate *)fire
{
appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.localNotification = [[UILocalNotification alloc] init];
NSLog(#"localNotification %#", appDelegate.localNotification);
if (appDelegate.localNotification == nil)
return;
appDelegate.localNotification.fireDate = fire;
appDelegate.localNotification.timeZone = [NSTimeZone defaultTimeZone];
appDelegate.localNotification.alertBody = appDelegate.str_Motivation;
appDelegate.localNotification.alertAction = #"View";
appDelegate.localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",appDelegate.str_Alarm];
appDelegate.localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
NSLog(#"localNotification.alertBody %#", appDelegate.localNotification.alertBody);
NSLog(#"localNotification.soundName %#",appDelegate.localNotification.soundName);
[[UIApplication sharedApplication] scheduleLocalNotification:appDelegate.localNotification];
}
Please Help.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
......
......
if (localNotif)
{
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(#"%# has a message for you.", nil), str_friend];
localNotif.alertAction = NSLocalizedString(#"Read Msg", nil);
localNotif.soundName = #"alarmsound.caf";
localNotif.applicationIconBadgeNumber = 1;
[localNotif setRepeatInterval:NSMinuteCalendarUnit];
[application presentLocalNotificationNow:localNotif];
str_friend = nil;
break;
}
}
I got solution.

Device is always showing that failed to regiseter for push notification

Im using the push notification service in my app.
But it is now always showing(when app launches) that it is failed to register for pushnotification.
i used the below code for push notifications:
Can anyone help me where i'm going wrong.
Thanks in advance.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if(application.applicationIconBadgeNumber != 0){
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:#"new"];}
[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];
NSLog(#"Registering for push notifications...");
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"asdfasdf");
NSString *str = [NSString
stringWithFormat:#"Device Token=%#",deviceToken];
const char* data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://chargrilled.k-hosting.co.uk/test2/register_device.php?dt=%#",token]];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]autorelease];
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:self];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Device registered for push notification."
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Okay", nil];
[alert show];
[alert release];
}
- (NSString*)stringWithDeviceToken:(NSData*)deviceToken {
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Device registration failed."
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Okay", nil];
[alert show];
[alert release];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
int i;
for (id key in userInfo) {
i++;
NSLog(#"key: %#, value: %#", key, [userInfo objectForKey:key]);
if(i==2){
}
}
application.applicationIconBadgeNumber = [[userInfo objectForKey:#"badge"] integerValue];
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:#"new"];
}
Check the profile u are using, is it enable for push notification. If not create a new with push notification.

Push Notification Device Token?

How to get Device Token from my iPhone Device?
this method will print the deviceToken in console in debug mode, if you want to see the device token you can see in UIAlert also.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APN device token: %#", deviceToken);
NSString *deviceTokenString = [NSString stringWithFormat:#"%#",deviceToken];
UIAlertView *deviceTokenAlert = [[UIAlertView alloc] initWithTitle:#"Device Token"
message:deviceTokenString
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
}
If you have implemented this method
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
}
for Push Notification then you will get the device token (This method is actually one of the two methods that you require to implement in the application)
This might find it useful http://urbanairship.com/docs/push.html
you can also look at Push Notification in Iphone application
I hope you find this useful.
This method will show your device token in console.
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString
stringWithFormat:#"%#",deviceToken];
NSString *newString = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"<" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#">" withString:#""];
[[NSUserDefaults standardUserDefaults] setObject:newString forKey:#"deviceToken"];
NSLog(#"Your deviceToken ---> %#",newString);
}