Why isn't this device token being printed to the NSLog? - ios

I am trying to print a device token to the Debugger Window. When building and running the app on a test device, the app receives a Would Like to Send You Push Notifications alert, but the NSLog doesn't print the device token.
//REGISTER FOR THE NOTIFICATIONS TYPES
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
//-- Set Notification
if (#available(iOS 8, *)) {
// iOS 8 Notifications: Registering for notifications and types
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
} else {
// iOS < 8 Notifications
_storyBoard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
if (launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSLog(#"Launched from push notification: %#", dictionary);
/*[self addMessageFromRemoteNotification:dictionary updateUI:NO];*/
}
}
return YES;
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
NSLog(#"Failed to get token, error: %#", error);
}
didFailToRegisterForRemoteNotificationsWithError isn't being called or printed either. How can this code be edited to print the device token in the NSLog?

Related

Registering for remote notifications does nothing

I have a button in my app that triggers registering for notifications. Say this is a UIBarButton.
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:#"Grant" style:UIBarButtonItemStyleDone target:self action:#selector(grantPermission:)];
self.navigationItem.rightBarButtonItem = rightButton;
This is the function the button triggers:
- (void)grantPermission:(id)sender {
if (SYSTEM_VERSION_LESS_THAN( #"10.0" )) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
NSLog(#"Completion handler called");
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
} else {
NSLog( #"Push registration FAILED" );
NSLog( #"ERROR: %# - %#", error.localizedFailureReason, error.localizedDescription );
NSLog( #"SUGGESTIONS: %# - %#", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
}
}];
}
}
I also added the following delegate methods:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Did Fail to Register for Remote Notifications");
NSLog(#"%#, %#", error, error.localizedDescription);
}
When I run this code, I get the modal asking for permission. When I press 'accept' I see the Completion handler called log, but nothing after that. Nothing happens, no logs are shown. Nothing. Any ideas as to what I'm doing wrong?
You must test that code on a physical device. Simulators don't get notifications token. You will get an error callback.
Also check which version of iOS you are targeting because the callbacks in the app delegate which changed between ios9-10 (possibly 11) so you will have a deprecated method which won't get called (or visa versa depending on which version of iOS you are testing against)

How to handle iOS remote notification while app is in background

I am working on iOS push notification functionality through apple push notification,right now i am getting proper notification while my app is in background or foreground,but i want to handle remote notification when my app is in background basically when my app is in background it is simply showing alert message from payload.Actually i just want to customize my remote notification.
code:
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
// Override point for customization after application launch.
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)];
}
return YES;
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", error);
}
- (void)application:(UIApplication )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData )deviceToken {
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", deviceToken);
}
-(void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (UIBackgroundFetchResult))completionHandler
{
NSDictionary * aps=[userInfo valueForKey"aps"];
NSLog(#"did recevie %#",aps);
NSLog(#"userinfo details %#",[aps valueForKey"alert"]);
}
In iOS 10 first you have to set UNUserNotificationCenterDelegate in AppDelegate.h file
#interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate>
After that in AppDelegate.m write code like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
// iOS 8 or later
// [START register_for_notifications]
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
{
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
[application registerForRemoteNotifications];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
Now implement this method for below iOS10 version
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);
if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( #"10.0" ) )
{
NSLog( #"iOS version >= 10. Let NotificationCenter handle this one." );
return;
}
NSLog( #"HANDLE PUSH, didReceiveRemoteNotification: %#", userInfo );
else{
handler( UIBackgroundFetchResultNewData );
}
}
Apple introduces these two methods in iOS10 to receive push notifications.
Write these methods also
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
NSLog(#"%#", userInfo);
completionHandler( UNNotificationPresentationOptionAlert );
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSLog(#"Userinfo %#",response.notification.request.content.userInfo);
// completionHandler(UNNotificationPresentationOptionAlert);
}
That's it.
Try this

remote notification are not displayed in ios using FCM

after deploying FCM cloud messaging which is the upgrading version of GCM cloud messaging as mentioned https://developers.google.com/cloud-messaging/ios/client so we moved to integrate FCM in our app using pod as mentioned https://firebase.google.com/docs/cloud-messaging/notifications i follow up every step in the tutorial here is what happening the remote notification had been received well in both state Background State and active state but the main problem that i faced is the notification does appear in the notification bar here is my code that i am using
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
float ver = [[[UIDevice currentDevice] systemVersion] floatValue];
if(ver >= 8 && ver<9)
{
if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)])
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
}else if (ver >=9){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else{
//iOS6 and iOS7 specific code
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert];
}
// ma tensa google maps
[FIRApp configure];
[self connectToFcm];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSLog(#"My token is: %#", deviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.applicationIconBadgeNumber = 0;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
NSLog(#"Message ID: %#", userInfo[#"gcm.message_id"]);
//
// if (application.applicationState == active) {
// <#statements#>
// }
// Pring full message.
NSLog(#"%#", userInfo);
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// [[FIRMessaging messaging] disconnect];
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"registeredToFCM"];
[[NSUserDefaults standardUserDefaults] synchronize];
// i used the method since not all the time app register for fcm so when
//the complete launching and did not register //
//for fcm the app request to register fro fcm again//
}
}];
}
here some link that i searched for to solve my problem before moving here Notifications are not getting in iOS 9.2 , FCM background notifications not working in iOS, and Push notifications are not working in iOS 9 but i could not solve my issue
Forgot to tell you that the phone is ringing and vibrating when the notification had been received.
hope any one help Happy Coding !!
If you want the notification to show up you have to set "priority":"high". Like so:
"to":"TOKEN ID",
"notification" : {
"body" : "test"
},
"priority": "high"
}

how to get Device Token in iOS?

I am working on push notifications. I wrote the following code for fetching a device token.
-(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(#"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
-(void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *str = [NSString stringWithFormat:#"Device Token=%#",deviceToken];
NSLog(#"This is device token%#", deviceToken);
}
-(void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
NSString *str = [NSString stringWithFormat: #"Error: %#", err];
NSLog(#"Error %#",err);
}
Try this code :
// Register for Push Notification
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)];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings // NS_AVAILABLE_IOS(8_0);
{
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
NSLog(#"deviceToken: %#", deviceToken);
NSString * token = [NSString stringWithFormat:#"%#", deviceToken];
//Format token as you need:
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
token = [token stringByReplacingOccurrencesOfString:#">" withString:#""];
token = [token stringByReplacingOccurrencesOfString:#"<" withString:#""];
}
Note : simulator not return deviceToken, deviceToken only return in device with valid APNS certificate
Enable "Push Notifications" in Xcode, this will fix the issue.
Targets -> Capabilities -> Push Notifications
Note:
Provisioning Profiles Should be in Active State
In iOS 8 and iOS 9 you need to register for notifications like this:
NSLog(#"Registering for push notifications...");
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
Note that if you also want to support iOS 7, then you'll need to call your existing code on the earlier versions of iOS.
Same issue happened with me So You have to use following code to get device token:-
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"content---%#", token);
}
Even then it doesn't work Then please check your provisioning profile,it should be of that app ID by which you have created your ssl certificate for push notification.
Here is the latest code of swift 4.0, so you can use following code to get device token.
import UserNotifications
if #available(iOS 10, *) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in
}
UIApplication.shared.registerForRemoteNotifications()
} else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined()
}
Get device token in Swift 3
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = String(format: "%#", deviceToken as CVarArg)
.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
.replacingOccurrences(of: " ", with: "")
print(token)
}

push notification : both didFailToRegister and didRegister delegate not calling

I am creating an application which support push notification
I am following all the steps.
It give error on simulator
Failed to get token, error: Error Domain=NSCocoaErrorDomain Code=3010 "remote notifications are not supported in the simulator" UserInfo=0x5813d20 {NSLocalizedDescription=remote notifications are not supported in the simulator}
But on device it not calling the delegates methods
didFailToRegisterForRemoteNotificationsWithError
didRegisterForRemoteNotificationsWithDeviceToken
My Code :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
NSLog(#"application didFinishLaunchingWithOptions");
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSLog(#"My Token is %#",deviceToken);
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(#"Failed to get token, error: %#", error);
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(#"Received Notification %#", userInfo);
}
Push notification won't work in iPhone's Simulator.
Try to check with device.
Solved for me:
In Device, go to:
`Settings->Notifications->YourApp->Enable_Notifications`
As said by #kalyan Push Notification will NOT work in Simulator
But if you want to get ride of the warning here is the code to work
with both Simulator and device (Check for TARGET_IPHONE_SIMULATOR )
and iOS7 and iOS8 ( Check for registerUserNotificationSettings )
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#if !TARGET_IPHONE_SIMULATOR
// New User Notification Settings for iOS8 support
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else { // for iOS 7
UIRemoteNotificationType remoteNotificationType = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
remoteNotificationType];
}
#endif
}

Resources