APNS can't get DeviceToken - ios

My code.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(#"~ios10-----");
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}else{
NSLog(#"~ios10---error--");
}
}];
This code in iPhone 5s ios 11.4.1 is work, didRegisterForRemoteNotificationsWithDeviceToken method called.
But in iPhone 6s ios 13.5.0 doesn't work. After few days of googled, in APNS connection failure
found a solution, fix was to change the phones to use an alternative DNS like Google (8.8.8.8) or Cloudflare (1.1.1.1) in the wifi settings. But I can't modify the DNS of the user's phone.
If you have any ideas, please let me know. Thanks

you can try this,i hope this will help you.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
#endif
}

Related

FCMToken always null in real device

I am trying to integrate Fireabase notification in iOS for 5 days.
But I can't get the fcmtoken in real device.
It always null.
Here is my code. This code is just from the firebase GitHub sample code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[FIRApp configure];
[FIRMessaging messaging].shouldEstablishDirectChannel = true;
[FIRMessaging messaging].delegate = self;
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {
// iOS 8 or later
// [START register_for_notifications]
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
//[FIRMessaging messaging].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
return YES; }
Adn I know I can get the femtoken on the didRefreshRegistrationToken delegate method.
The method is fired well on the simulator, but never fired on real device.
And after [FIRApp configure], I tried to get the fcmtoken with this method [[FIRInstanceID instanceID] token],but still token is null.
I have done googling as much as I can do, but get the proper answer on the google.
Please help me.
Any help would be appreciate for me

Firebase push notification doesn't work after a few weeks

I am using Firebase Cloud Messaging in my app. It worked fine for a few weeks, but these last two days, it doesn't.
I send the messages from the Firebase Console. I handle the token refresh. What can be the problem?
This is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[self registerForPush];
}
Here is where I register for Push Notifications:
-(void)registerForPush
{
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} 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)
{
if (error)
{
NSLog(#"\n\n %# \n\n",error.description);
}
NSLog(#"");
}];
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
// For iOS 10 data message (sent via FCM)
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
Did register for Remote Notifications with Device Token:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[FIRInstanceID instanceID] token];
NSLog(#"%#", token);
// Add observer to listen for the token refresh notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onTokenRefresh) name:kFIRInstanceIDTokenRefreshNotification object:nil];
if(token)
{
[self subscribeToTopics];
}
}
this the Observer for when firebase refresh token :
- (void)onTokenRefresh
{
// Get the default token if the earlier default token was nil. If the we already
// had a default token most likely this will be nil too. But that is OK we just
// wait for another notification of this type.
NSString *token = [[FIRInstanceID instanceID] token];
if (token)
{
[self subscribeToTopics];
}
}
this is my subscribe to firebase topics :
-(void)subscribeToTopics
{
[[FIRMessaging messaging] subscribeToTopic:#"/topics/ios"];
[[FIRMessaging messaging] subscribeToTopic:#"/topics/all"];
#ifdef DEBUG
[[FIRMessaging messaging] subscribeToTopic:#"/topics/developer_devices"];
#else
[[FIRMessaging messaging] unsubscribeFromTopic:#"/topics/developer_devices"];
#endif
}
Your APNs certificate has probably been revoked for some reason. Try generating a new one and re-uploading it in the firebase console!
https://firebase.google.com/docs/notifications/ios/console-audience#upload_your_apns_certificate

FCM Notification not working in Production mode, works in Development

I am implementing push notification for iOS app using FCM. my Pushnotification API is made in C#.net.
My problem is that when my application was in development mode, notification works, but after made binary (from : diawi.com) for client, the notification did not work anymore, even if I am getting a success message from server.
I followed many links from StackOverflow, but no success.
API Code :
var applicationID ="AAAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxCUxxxxeA";
var senderId = "2771xxxxxx16";
deviceIdAsus = "cEOfJfqoxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMpGc";
body = "Pushnotification Iphone TestMessage";
title = "Test";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceIdAsus,
notification = new
{
body = body,
title = title,
icon = "myicon",
sound = "default",
},
data = new
{
body = body,
title = title,
icon = "myicon",
sound = "default",
},
priority = "high"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
response = sResponseFromServer;
}
}
}
}
Reponse :
{
"Status": "True",
"Response": "{\"multicast_id\":5525338412933884291,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1482845931819882%b367a02ab367a02a\"}]}"
}
IOS Code (Objective c) :
#define Application_Type #"Production"
Appdelegate.m
didFinishLaunchingWithOptions{
if (floor(NSFoundationVersionNumber) < NSFoundationVersionNumber10_0) {if (floor(NSFoundationVersionNumber) < NSFoundationVersionNumber10_0) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]10_
requestAuthorizationWithOptions:authOptions
];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications]; UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[UIApplication.sharedApplication registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound];
[application registerForRemoteNotifications];
}
[FIRApp configure];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(onTokenRefresh)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)settings{
NSLog(#"Registering device for push notifications..."); // iOS 8
if (floor(NSFoundationVersionNumber) < NSFoundationVersionNumber10_0) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSLog(#"deviceToken %#",deviceToken);
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
_strDeviceToke = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
if (_strDeviceToke) {
NSLog(#"Device %#",_strDeviceToke);
#if DEBUG
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
#else
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
#endif
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(#"FireBase InstanceID token: %#", refreshedToken);
if (refreshedToken.length ==0) {
_strFireBaseToken =refreshedToken;
[[NSUserDefaults standardUserDefaults]setValue:refreshedToken forKey:#"NotificationToken"];
}
[self connectToFcm];
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
if (application.applicationState == UIApplicationStateActive) {
[application setApplicationIconBadgeNumber:0];
}else if (application.applicationState==UIApplicationStateBackground){
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
} else {
}
}];
}
and change Code siging ->Provisional profile ->Release ->Distribution certificate
Can anyone point me in the right direction?

FIRInstanceID token null thel first time app starts, OK the second time

I am implementing Firebase push notifications on my iOS app.
On didFinishLaunchingWithOptions, I call [FIRApp configure]. It returns nill token the first time the app starts, but if I run the app again, it returns a valid working token.
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
null the first time.
Here's the code in application didFinishLaunchingWithOptions::
- (void)handleFCMregister
{
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} 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];
// For iOS 10 data message (sent via FCM)
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
[FIRApp configure];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
DLog(#"refreshedToken ::%#", refreshedToken);
}
How to get a valid token the first time the app starts? What seems to be wrong? Thanks.

How to implement push notification for iOS 10[Objective C]?

Can anyone help me with implementing push notification for iOS 10 as i have implemented following code but still getting problem in it:
#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(#"10.0"))
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!error){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
}
else {
// Code for old versions
}
I am getting error suggesting that
Unknown receiver UIUserNotificationCenter
Thank you in advance!
Sorry guys, I got the answer.
I just needed to import UserNotifications framework.
#import <UserNotifications/UserNotifications.h>
Check this
#import <UserNotifications/UserNotifications.h>
Then
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
#endif
}

Resources