Device token in push notification - iphone

I want to send push notification to certain users only.
From what I have gone through in Apple docs.
The code to register for push notification is this
- (void)applicationDidFinishLaunching:(UIApplication *)app {
// other setup tasks here....
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
[self sendProviderDeviceToken:devTokenBytes]; // custom method
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
In the method appdidRegisterForRemoteNotif..I see only devToken bytes created and send to the server..but how will I identify which device token belongs to which user. So if my device name is Shubhank's iPhone. How can I send the information that my iPhone is this and this is my device token.

generally you don't update the apns token on server in the delegate method itself. you save it and update it later when you have the user identified.
You can do it this way:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:#"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
[[MyModel sharedModel] setApnsToken:hexToken];
}
with this you saved the apns token in the Model object (MyModel). And later when you have your user identified (by login/sign up or whatever method)
you can call this method
[self sendProvidedDeviceToken: [[MyModel sharedModel] apnsToken] forUserWithId: userId]; //Custom method
This way you have linked the device token with user. Hope this helps!

You need to send the device name when registering in your custom method. The code should look something like below. You could send along any information that is appropriate for your context, like a username if the application uses some kind username. It is up to you which to decide which information to send to your server that makes a connection between the token and the device.
// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
[self sendProviderDeviceToken:devTokenBytes deviceName:[[UIDevice currentDevice] name]]; // custom method
}

It's up to you to send whatever information you need to your own push service.
But an important point: the push token is not the device token (UDID). Push tokens are unique to each app that requests them, and can and do change. If you want to get the device name in addition to that, you can call [[UIDevice currentDevice] name], and post it off to whatever you are using to store your push tokens.

Related

Turn Push Notifications On and Off from within App with Parse

I have been advised that I should allow users to turn push notifications on and off from within my app. I am using Parse to manage my push notifications. I have everything setup so that a user can register for notifications by pressing "Allow." when the push alert pops up. My question though, is about how I would permit the user to turn push notifications ON from within the app if they had originally said "Don't Allow." I know that the push notification alert will only display once. Does anyone have any ideas? Thanks!
My App Delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions {
[Parse setApplicationId:#"APP_ID"
clientKey:#"CLIENT_KEY"];
[PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
//other code
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Store the deviceToken in the current installation and save it to Parse.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
[currentInstallation saveInBackground];
}
User Settings View Controller:
-(IBAction) switchValueChanged {
if (toggleSwitch.on) {
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:deviceToken];
[currentInstallation saveInBackground];
}
else {
}
}
You cannot do that. The user has to manually go into the Notification Settings and set your app for notifications. Apparently the reason being is that Apple does not want an app pestering a user to allow if the user has already said no once.
I suggest having your app display an alert to advise the user of turning notifications on.

Parse push notification in iphone

Integrated parse push notification in iOS project. Not working.
Here is my code:
#ifdef ENABLE_PARSE_PUSH
#import "Parse/Parse.h"
#endif
//in appDelegate didFinishLaunchingWithOptions
#ifdef ENABLE_PARSE_PUSH
// Obtain the installation object for the current device
[Parse setApplicationId:PARSE_APP_ID clientKey:PARSE_APP_SIGNATURE];
PFInstallation *myInstallation = [PFInstallation currentInstallation];
// Save some data
[myInstallation setObject:#"YES" forKey:#"scoreUpdates"];
// Save or Create installation object
[myInstallation saveInBackground];
[application registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
#ifdef ENABLE_PARSE_PUSH
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
[PFPush storeDeviceToken:newDeviceToken]; // Send parse the device token
// Subscribe this user to the broadcast channel, ""
[PFPush subscribeToChannelInBackground:#"" block:^(BOOL succeeded, NSError *error) {
if (succeeded)
{
//#ifdef DEBUG
//NSLog(#"Successfully subscribed to the broadcast channel.");
//#endif
}
else
{
//#ifdef DEBUG
//NSLog(#"Failed to subscribe to the broadcast channel.");
//#endif
}
}];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
}
#endif
here is one similar post not helped for me..tried all suggested solutions. What's wrong..already uploaded development push SSL in parse.com. help me to get solution.
Now test push message from parse.com is not delivering in device.
Hi Have you try this Parse step by step Tutorial
https://www.parse.com/tutorials/ios-push-notifications
Follow the tutorial and if you get stack you can post here for help .
Ok Finally resolved this problem.
• We need to create new provisioning profile after configuring push SLL in app id section. Then we need to use new provisioning profile.
This solved my problem and now getting test push message from Parse.

Cancel Remote Notifications ,let it not show at the notification center

My app is close ,and screen is lock,when I receive a remote push notification,it appear on the screen,when I slide the notification but not slide the lock,it can open my app,all is OK.but the notification always appear at notification center,not disappear. How to dismiss it from the notification center,when I slide the notification.
(void)applicationDidFinishLaunching:(UIApplication *)application{
// put receive remote notification is here
}
is there have some api like cancel localnotificationg,cancel remote notification?
Set the applicationIconBadgeNumber property of your UIApplucation object to zero. This will clear tge notifications from notification center.
Where you handle the notification, you need to reset applicationIconBadgeNumber property.
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
This should be ideally at the place of Custom Code in following snippet:
- (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);
badgeValue= [alertValue intValue];
[UIApplication sharedApplication].applicationIconBadgeNumber += badgeValue;
//
//Custom Code where you actually respond to the notification.
//
}

User taps on UILocalNotification: Can it pass data to the app?

I am creating a local UILocalNotification and displaying it to the user as a banner. Is it possible to set it up so that when the user taps it and returns to the app, the app will receive some kind of data on the specific kind of notification it was? I want to open a specific view controller in the app. I think the best way would be to essentially send a URL to the app, or is there a way to get access to the UILocalNotification so that I can test which kind is was and do the right action?
To get data from the local NSUserNotification that is passed to an iOS app, all that you need to do is implement the following method: - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification.
The problem is, this is called both when a local notification is posted when the app is in the background (i.e. when the user taps on the notification and then returns to the app), and also if the app is in the foreground at the time when the local notification fires (it is on a timer, after all). So how should one figure out if the notification was fired when the app was in the background or foreground? It's pretty simple. Here's my code:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateInactive) {
// Application was in the background when notification was delivered.
} else {
// App was running in the foreground. Perhaps
// show a UIAlertView to ask them what they want to do?
}
}
At this point you can handle the notification based on notification.userInfo, which holds a NSDictionary.
ust implement the NSUserNotificationCenterDelegate and define this method:
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
Example:
This is what I did in a "notifier" application.
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
NSRunAlertPanel([notification title], [notification informativeText], #"Ok", nil, nil);
}
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
notifications=nil;
[tableView reloadData];
[center removeDeliveredNotification: notification];
}
When the notification is activated (click by the user) I just inform the user with a panel (I could use a hud window).In this case I immediately remove the delivered notification, but this is not what happens usually.The notification could stay there some time and be removed after 1/2 hours (it depends on the application that you are developing).
1 - Define some class in your project to implement NSUserNoficationCenterDelegate protocol (documented here)
#interface someObject : NSObject <NSUserNotificationCenterDelegate>
{
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;
}
2 - Set an instance of the object defined #1 as the delegate of default notification center.
[[NSUserNotificationCenter defaultNotificationCenter] setDelegate: someObject];
Now you will get called on didActivateNotification any time the user taps/clicks on the notification. You will have the original notification you created. So any information that you need should be available to you.
If you want/need special information (other than notification title, message, etc) you will probably need to set additional application specific information in your notification before you schedule it to be sent. For example:
NSUserNotification* notification = [[NSUserNotification alloc] init];
NSDictionary* specialInformation = [NSDictionary dictionaryWithObjectsAndKeys: #"specialValue", #"specialKey", nil];
[notification setUserInfo:specialInformation];

How to take the text string from the push notifications?

I have an Iphone application in which i am recieving push notifications from the server.Now i am going to a view controller to show the message.Where that same message is loaded in a tableview .so thats not a problem.Now i am recieving two kinds of messages,one is a link and another is the message as earlier.if it is a link i want to open it in saffari,not need to go to tableview as usual.Can anybody help me to achieve this?
When You click on the push notification then you get a dictionary in the function - didReceiveRemoteNotification:
try this code:-
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"remote notification: %#",[userInfo description]);
if (userInfo)
{
if ([[userInfo allKeys] containsObject:#"aps"])
{
if([[[userInfo objectForKey:#"aps"] allKeys] containsObject:#"alert"])
{
if([[[userInfo objectForKey:#"aps"] allKeys] containsObject:#"alert"])
{
NSString *urlString = [[userInfo objectForKey:#"aps"] objectForKey:#"alert"];
NSURL *url = [NSURL URLWithString:urlString];
if(url)
{
[[UIApplication sharedApplication]openURL:url]; // open in the safari...
}
else
{
// use the message in table view
}
}
}
}
}
}
The push notification is tied to your application, so in short its not possible to have a push notification from you application open safari directly. However, one workaround might go something like this:
user responds to notification (ie swipes to open it on the lock screen)
your app opens, and the data from the notification is passed into your applications
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method. You could then interrogate the the data passed in as so
NSDictionary *dictionary = [launchOptions objectForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"];
// If dictionary is not nil, then your app is launched due to a push notification
if (dictionary != nil) {
NSDictionary *payload = [tmpDic objectForKey:#"aps"];
}
Once you've got your payload, look at the contents, and if it is a URL, call the safari URL scheme, passing in the URL. Like so
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: <URL from payload>]];
This will help you achieve what you want to do, but it may mean the user briefly sees your app first before the os will switch them into safari.
A side note, why would you want to do this? Your users should not be launching a random URL from a notification, and I don't think Apple would like that too much. Prehaps they should be seeing some information about the URL first in your app, and then choosing whether they would like to open it in safari?