How to get GCM Notifications in ios - ios

Hi I am a beginner in iOS. In my project I want to get GCM notifications for that I have written some code but it shows exception and my code is as following :
#import "AppDelegate.h"
#import <Google/CloudMessaging.h>
#import "GGLInstanceID.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound |
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
_registrationHandler = ^(NSString *registrationToken, NSError *error){
if (registrationToken != nil) {
weakSelf.registrationToken = registrationToken;
NSLog(#"Registration Token: %#", registrationToken);
NSDictionary *userInfo = #{#"registrationToken":registrationToken};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
NSDictionary *userInfo = #{#"error":error.localizedDescription};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
}
};
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
_registrationOptions = #{kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#YES};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
}
But it's shows Exception like
unresolved identifier "_registrationHandler" and "weakSelf" in
didFinishLaunchingWithOptions method and it exception in
didRegisterForRemoteNotificationsWithDeviceToken method like
unresolved identifier "_registrationOptions".
Please help me someone

Here I've refactored your code and it should work now.
static NSString *const INSTANCE_ID_REGISTRATION_NOTIF_KEY = #"instance-id-token";
static NSString *const GCM_SENDER_ID = #"<your sender id>"; // #"123456"
#interface AppDelegate ()
#property (nonatomic, strong, readwrite) GGLInstanceIDTokenHandler registrationHandler;
#property (nonatomic, strong, readwrite) NSString *registrationToken;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound |
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[GGLInstanceID sharedInstance] startWithConfig:[GGLInstanceIDConfig defaultConfig]];
NSDictionary *registrationOptions = #{
kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:#YES
};
__weak typeof(self) weakSelf = self;
GGLInstanceIDTokenHandler handler = ^(NSString *registrationToken, NSError *error){
typeof(weakSelf) strongSelf = weakSelf;
NSDictionary *userInfo;
if (registrationToken != nil) {
strongSelf.registrationToken = registrationToken;
NSLog(#"Registration Token: %#", registrationToken);
userInfo = #{ #"registrationToken" : registrationToken };
} else {
NSLog(#"Registration to GCM failed with error: %#", error.localizedDescription);
userInfo = #{ #"error" : error.localizedDescription };
}
[[NSNotificationCenter defaultCenter] postNotificationName:INSTANCE_ID_REGISTRATION_NOTIF_KEY
object:nil
userInfo:userInfo];
};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:GCM_SENDER_ID
scope:kGGLInstanceIDScopeGCM
options:registrationOptions
handler:handler];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Notification received: %#", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
}
#end
PS: As #Epaga commented above you should really try to start off with a simple obj-c tutorial because your compiler issues were very trivial.

Related

Firebase Cloud Messaging is not working on iOS 12

I have set up everything according to https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in
However, I am not receiving any messages.
My APN certificate (p.12) expired, I had to add a new APN key (p.8) (I think there is no issue here.)
I am not receiving anything in my log, after the app enters background.
Also, there are no error messages.
I am confused, it used to work on iOS 11.
What is my mistake here?
#implementation AppDelegate
NSString *const kGCMMessageIDKey = #"gcm.message_id";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(#"APPDIDFINISHLAUNCH called with options: %#", launchOptions);
[FIROptions defaultOptions].deepLinkURLScheme = #"xxxxx";
[FIRApp configure];
[FIRMessaging messaging].delegate = self;
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Error fetching remote instance ID: %#", error);
} else {
NSLog(#"Remote instance ID token: %#", result.token);
NSString* message =
[NSString stringWithFormat:#"Remote InstanceID token: %#", result.token];
}
}];
if ([UNUserNotificationCenter class] != nil) {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
} else {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
}
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
NSLog(#"ssaging messaging].APNSToke");
}
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSLog(#"didReceiveMessage: %#", remoteMessage);
}
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:#"token"];
[[NSNotificationCenter defaultCenter] postNotificationName:
#"FCMToken" object:nil userInfo:dataDict];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
completionHandler(UIBackgroundFetchResultNewData);
}
I am happy for any help.

iOS Firebase notifications only appear in background

I have an iOS app with Firebase messaging added. The problem is the firebase push notifications only appear if the app is terminated or in the background. I'd like to be able to handle the message programmatically and display some kind of modal, but the didReceiveRemoteNotification method isn't even being called.
Here is my AppDelegate.m
#import "AppDelegate.h"
#import "MainViewController.h"
#import "AppName-Swift.h"
#import Firebase;
#import FirebaseMessaging;
#import FirebaseInstanceID;
#implementation AppDelegate {
LocationSyncManager* locationSyncManager;
bool isLocationLaunch;
}
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
isLocationLaunch = [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey];
[FIRApp configure];
[FIRMessaging messaging].delegate = self;
[self enablePushNotifications:application];
if(isLocationLaunch) {
if(AccountStore.shared.account != nil) {
locationSyncManager = [LocationSyncManager shared];
[locationSyncManager enable];
}
} else {
self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
return nil;
}
- (void) enablePushNotifications:(UIApplication*)application {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
}
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveRegistrationToken:(nonnull NSString *)fcmToken {
[LocationSyncManager shared].deviceToken = fcmToken;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
[FIRMessaging messaging].shouldEstablishDirectChannel = YES;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"--- didFailToRegisterForRemoteNotificationsWithError %#", error);
}
// In case the user tries to open the app while it is running in the background,
// allow the webview to initialize and disable the isLocationLaunch flag.
- (void)applicationWillEnterForeground:(UIApplication *)application {
if(isLocationLaunch) {
self.viewController = [[MainViewController alloc] init];
[self application:application didFinishLaunchingWithOptions:nil];
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"---- RECEIVED REMOVE NOTIFICATION %#", userInfo);
}
#end
I should be seeing ---- RECEIVED REMOVE NOTIFICATION in the logs after the server sends a PN, but it's not happening. Why isn't didReceiveRemoteNotification called in the foreground?

Issue subscribing to FCM topic using Xcode/Objective C

I have a problem which I've been unable to resolve. My knowledge of iOS/Xcode is limited, please forgive me.
I am trying to subscribe to an FCM topic for an iOS app using xcode/Objective C but when loading the App, it is not subscribing to the topic, in the debugger it doesn't even look like it is trying.
If I move the [[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
line to just below
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
(and above return YES;) then at least I get this error message indicating that it is at least trying.
2018-01-04 04:00:18.723760+0000 App[1049:1251125] [Firebase/Messaging][I-FCM002010] Cannot subscribe to topic: /topics/channel with token: (null)
So following the suggestion here (and a number of other places), I have tried to move it out into didRegisterUserNotificationSettings but it doesn't seem to be doing anything at all and there is no trace of it in the debugger.
This is my full AppDelegate.m code
//
// AppDelegate.m
//
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import <Firebase/Firebase.h>
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <FirebaseInstanceID/FirebaseInstanceID.h>
#import <AFNetworking/AFNetworking.h>
#import Firebase;
#interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupNetworkReachability];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error)
{
}];
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
[FIRApp configure];
//[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
return YES;
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UNNotificationSettings *)notificationSettings
{
[[FIRMessaging messaging] subscribeToTopic:#"/topics/channel"];
NSLog(#"Topic Registered");
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
#pragma mark - Public Methods
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (void)setupNetworkReachability
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN)
self.isNetworkAvailable = YES;
else
self.isNetworkAvailable = NO;
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
#pragma mark - FIRMessagingDelegate Methods
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
{
NSLog(#"%#", remoteMessage.appData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(#"%#", notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}
#end
Would appreciate any help. Thank you.
Just to update, the App already receives message directly from FCM console, so that part works OK, it is just the topic subscription that is failing.
1: You should call [FIRApp configure]; before [FIRMessaging messaging].delegate = self;
2: As you post full code of your AppDelegate.m file. So it is missing the below method to update/send token to Firebase. You will receive a TOKEN with in this UIApplication's delegate method and you have to set it for Firebase (Just put this method in your AppDelegate.m file)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *strDevicetoken = [[NSString alloc]initWithFormat:#"%#",[[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] stringByReplacingOccurrencesOfString:#" " withString:#""]];
NSLog(#"Device Token = %#",strDevicetoken);
[FIRMessaging messaging].APNSToken = deviceToken;
//NSString *fcmToken = [FIRMessaging messaging].FCMToken;
//NSLog(#"FCM registration token: %#", fcmToken);
}
Now you have successfully set APNS Token at Firebase and you can now subscribe to your desired topic at Firebase

Pushkit with Sinch VOIP not working with pushkit

I am trying to implement App-to-App calling with Sinch in my IOS app. I have implemented Pushkit in my iOS app with Sinch but the push notification is not working when the app is in background.
I have two questions.
Do I need another web service to send push notification to my app for incoming app separately or Sinch handles it itself.
If it does handle itself then what am I missing in my code.
#import "AppDelegate.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
[self handleLocalNotification:[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]];
self.push = [Sinch managedPushWithAPSEnvironment:SINAPSEnvironmentAutomatic];
self.push.delegate = self;
[self.push setDesiredPushTypeAutomatically];
[self.push registerUserNotificationSettings];
return YES;
}
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary *)options {
return [[GIDSignIn sharedInstance] handleURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[GIDSignIn sharedInstance] handleURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (id<SINClient>)client {
return _sinchClient;
}
-(void)clientDidFail:(id<SINClient>)client error:(NSError *)error{
NSLog(#"fail");
}
-(void)clientDidStart:(id<SINClient>)client{
NSLog(#"Start");
[self voipRegistration];
}
- (void)client:(id<SINClient>)client
logMessage:(NSString *)message
area:(NSString *)area
severity:(SINLogSeverity)severity
timestamp:(NSDate *)timestamp {
// If you want all messages remove the if statement
if (severity == SINLogSeverityCritical) {
NSLog(#"%#", message);
}
}
- (void)initSinchClientWithUserId:(NSString *)userId {
if (!_sinchClient) {
_sinchClient = [Sinch clientWithApplicationKey:#"<my-key>"
applicationSecret:#"<my-secret>"
environmentHost:#"sandbox.sinch.com"
userId:userId];
_sinchClient.delegate = self;
[_sinchClient setSupportCalling:YES];
[_sinchClient startListeningOnActiveConnection];
[_sinchClient enableManagedPushNotifications];
[_sinchClient start];
}
}
- (void)handleLocalNotification:(UILocalNotification *)notification {
if (notification) {
id<SINNotificationResult> result = [self.sinchClient relayLocalNotification:notification];
if ([result isCall] && [[result callResult] isTimedOut]) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Missed call"
message:[NSString stringWithFormat:#"Missed call from %#", [[result callResult] remoteUserId]]
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
}
}
}
-(void)voipRegistration
{
PKPushRegistry* voipRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
voipRegistry.delegate = self;
voipRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
}
-(void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
{
[_sinchClient registerPushNotificationData:credentials.token];
}
-(void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type{
NSLog(#"invalidated");
}
-(void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType: (NSString *)type
{
//notify
NSDictionary* dic = payload.dictionaryPayload;
NSString* sinchinfo = [dic objectForKey:#"sin"];
UILocalNotification* notif = [[UILocalNotification alloc] init];
notif.alertBody = #"incoming call";
[[UIApplication sharedApplication] presentLocalNotificationNow:notif];
if (sinchinfo == nil)
return;
dispatch_async(dispatch_get_main_queue(), ^{
[_sinchClient relayRemotePushNotificationPayload:sinchinfo];
});
}
If you integrated Pushkit and Sinch then push notification may can't catch on PushKit's delegate function - didReceiveIncomingPushWithPayload. But you can get push notification on SINManagedPushDelegate's function - didReceiveIncomingPushWithPayload.
Push notification is not coming but you can get incoming call event on there when app is in background. You can trigger local notification if app is in background to let user incoming call know.
Hope that would be helpful for you.

Is there a way to open urls received in a push notification without opening the app in ios 10?

I am trying to open a url that is passed in a push notification in ios 10.
So far I haven't found a way to open a the url without opening the app.
Is there a way to open urls received in a push notification without opening the app?
I have found a work-around to open the url (the work-around works for ios <10), but then again the app opens up first.
Update:
I've noticed that for the device (iOS 10.0)
The following mentohds get involked
application:didRegisterForRemoteNotificationsWithDeviceToken
userNotificationCenter:willPresentNotification:
userNotificationCenter:didReceiveNotificationResponse:
But -application:didReceiveRemoteNotification:fetchCompletionHandler: and -application:didReceiveRemoteNotification: aren't called.
I'm new to ios and this is how far I have gotten:
AppDelegate.h
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m
#import "AppDelegate.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10)
{
UNUserNotificationCenter * notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
notificationCenter.delegate = self;
[notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * error)
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
if (error)
{
NSLog(#"Auth. error:%#",[error localizedDescription]);
}
}];
[notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * settings) {
}];
}
else
{
UIUserNotificationType type = UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;
UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
return YES;
}
...
#pragma mark Push Notification methods
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(#"didReceiveRemoteNotification:");
NSString * message = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSString * urlString = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"1 Received Push URL: %#", urlString);
NSURL * url = [NSURL URLWithString:urlString];
if(url!=nil)
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
// iOS 10 and above
[[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
}
else
{
[[UIApplication sharedApplication] openURL:url]; // iOS <10
}
}
if (application.applicationState == UIApplicationStateInactive)
{
NSLog(#"Application inactive");
[[NSUserDefaults standardUserDefaults] setValue:message forKey:#"Push_Message"];
}
else if (application.applicationState == UIApplicationStateBackground)
{
NSLog(#"Application in background");
}
else
{
NSLog(#"Application active");
}
}
#pragma mark Notification Registration methods
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString* token = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken:\n%#",token);
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Error:%#",[error localizedDescription]);
NSLog(#"Suggest:%#",[error localizedRecoverySuggestion]);
}
#pragma mark App Push notification methods
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
NSLog(#"didRegisterUserNotificationSettings");
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"UserInfo: %#",userInfo);
NSString * messageString = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"Message:%#",messageString);
NSString * messageurl = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
NSLog(#"2 Received Push URL: %#", messageurl);
NSURL * url = [NSURL URLWithString:messageurl];
if(url!=nil)
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
// iOS 10 and above
[[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
}
else
{
[[UIApplication sharedApplication] openURL:url]; // iOS <10
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"PushMessage" object:self userInfo:#{#"alertString":messageString}];
}
#pragma mark UNUserNotificationCenterDelegate methods
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
NSLog(#"didReceiveNotificationResponse");
//--URL click--//
//Kindly suggest what can be done here?
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
NSLog(#"willPresentNotification");
completionHandler(UNNotificationPresentationOptionAlert);
}
#end
Hopefully you can't control the behaviour of the push before launching the app. You get control over the push only after the app launched.

Resources