I am using UrbanAirship to send push messages to my applications. my setting works both on development and production.
I need to send web url's as push message. when user opens the message I want it to redirect to the url that I added.
I added this code to my appdelegate.
`- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(#"userInfo:%#",[userInfo description]);
NSLog(#"alert:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]);
NSLog(#"alert:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"url"]);
}
and tried to send push like
{
"aps":
{
"alert": "take a look at this site ",
"url": "www.mysite.com"
}
}
I received the alert message but again it opened the application not the url.
Can you advice me how to send the push message with the url and make it open that url?
There is two way to do that
Open the url with a safari (not tested code):
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo
{
NSLog(#"userInfo:%#",[userInfo description]);
NSLog(#"alert:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]);
NSLog(#"url:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"url"]);
webViewController.url = [NSURL URLWithString:[[userInfo objectForKey:#"aps"] objectForKey:#"url"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSURL URLWithString:[[userInfo objectForKey:#"aps"] objectForKey:#"url"]];
}
Or you must to handle it on your app:
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo{
NSLog(#"userInfo:%#",[userInfo description]);
NSLog(#"alert:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]);
NSLog(#"url:%#",[[userInfo objectForKey:#"aps"] objectForKey:#"url"]);
webViewController.url = [NSURL URLWithString:[[userInfo objectForKey:#"aps"] objectForKey:#"url"]];
}
And e.g in your WebViewController need the following methods
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}
Of course, on your WebViewController.h must be a
IBOutlet UIWebView *webView;
with full screen, or what you want...
Related
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.
Im developing APNS.
When I send APNS, provide url and move the url.
APNS was succeed but When The app was running, it couldn't receive notification on foreground.
However on the background, it's work. when it's on foreground
it just move to url without notification.
Could you help me..?
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIApplicationState state = [UIApplication sharedApplication].applicationState;
BOOL state_active = (state == UIApplicationStateActive);
dic_apns = [userInfo objectForKey:#"aps"];
// alert export
NSString * msg = [dic_apns objectForKey:#"alert"];
NSString * eventcode = [userInfo objectForKey:#"eventcode"];
[[NSUserDefaults standardUserDefaults] setValue :msg forKey:#"push_msg"];
[[NSUserDefaults standardUserDefaults] setValue :eventcode forKey:#"eventcode"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"APNS : msg=%# | eventcode=%#", msg , eventcode);
[self goto_link];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
-(void) goto_link{
NSString * eventcode = [[NSUserDefaults standardUserDefaults] valueForKey:#"eventcode"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#", _MAIN_URL, _PUSH_PARAM, eventcode]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
ViewController* main = (ViewController *) self.window.rootViewController;
if (!main.webview_sin )
{
NSLog(#"main.webView is nil!!!");
}
[main.webview_sin loadRequest:request];
}
when it's on foreground it just move to url without notification
This is the expected behaviour. Notifications aren't shown if your app is running.
You could instead use a UIAlertController to show the message to the user
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (application.applicationState == UIApplicationStateActive)
{
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"Notification"
message:/* Get the message from APS */
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:#"Dismiss"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
//Do Nothing
}];
[alertController addAction:cancelAction];
[/*pick an appropriate view controller */ presentViewController:alertController animated:YES completion:nil];
}
}
Some code was adapted from here
The push notification only works when the app is in background ,But it didn't work when i removed it from background also when it returned to background , i didn't receive any push notifications. I had to delete the app and download it again from testflight to be able to receive push notifications.
here's the code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
//Do stuff that you would do if the application was not active
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSLog(#"Aps Info : %#",apsInfo);
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
#endif
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSInteger pushCode = [userInfo[#"pushCode"] integerValue];
NSLog(#"Silent Push Code Notification: %i", pushCode);
NSDictionary *aps = userInfo[#"aps"];
NSString *typeID = userInfo[#"type_id"];
NSString *alertMessage = aps[#"alert"];
NSLog(#"Type ID %#",typeID);
NSArray * array =[typeID componentsSeparatedByString:#","];
NSLog(#"Item %#,Item2 %#",[array objectAtIndex:0],[array objectAtIndex:1]);
[self typeID:[array objectAtIndex:0] userID:[array objectAtIndex:1] message:alertMessage];
NSLog(#"apss%#,alert%#,%#",aps,alertMessage,userInfo);
}
The problem is in the method:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
}
you should "catch" the notifications which arrive in background with this method:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
}
the fetchCompletionHandler method is designed for receiving "silent" push messages, which gets called prior to didReceiveRemoteNotification, if implemented.
Hi i have added push notification in my application and I want to view particular ViewControllers when the user tap the notification. In my app delegate m file I'm trying to get the register the device token to my server and from my server I'm using the php script to get the device token from server and I'm sending the notification.
The problem here I'm trying to view a particular view controller when the user taps on the notification its not working i have tried many different methods nothing had worked.
Here I'm view the popup like to send notification from the app when user trying to install application for the first time.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeNone)];
return YES;
}
- (void) clearNotifications {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
Here I'm storing the device to token to my server.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
const char* data = [deviceToken bytes];
NSMutableString * token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
NSString *urlString = [NSString stringWithFormat:#"url?token=%#",token];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSLog(#"token %#",urlString);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSLog(#"request %# ",urlRequest);
NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
NSLog(#"data %#",urlData);
[self clearNotifications];
// NSLog(#"token ",sendUserToken);
}
Here I'm trying to view the particular method when user tap the notification.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
updatepoliticalViewController *ringingVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
[self.window.rootViewController presentViewController:ringingVC animated:YES completion:NULL];
}
My particular view controller name is updatepoliticalViewController its a navigation view controller please tell me in this above code where I'm doing wrong how to resolve this issue.
Thanks
When the app is in foreground state it call
application:didReceiveRemoteNotification:
but if it's not and the app is launched, for example, by swiping the alert in notification center
application:didFinishLaunchingWithOptions:
is called with key.
The good way is to call
application:didReceiveRemoteNotification:
from
application:didFinishLaunchingWithOptions:
I believe this should help
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
[self application:application didReceiveRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
}
// YOUR CODE...
return YES;
}
// EXTENDED
Try get storyboard like that:
// Make sure the name match
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
Create your object from mainstoryboard:
updatepoliticalViewController *ringingVC = [mainstoryboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
And try set new root view controller
[self.window setRootViewController: ringingVC];
1) When application is running in background and When application is running in foreground
application:didReceiveRemoteNotification: method will called as below.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if ( application.applicationState == UIApplicationStateInactive)
{
//opened from a push notification when the app was on background
NSLog(#"userInfo->%#",[userInfo objectForKey:#"aps"]);
}
else if(application.applicationState == UIApplicationStateActive)
{
// a push notification when the app is running. So that you can display an alert and push in any view
NSLog(#"userInfo->%#",[userInfo objectForKey:#"aps"]);
}
}
2) When application is not launched (close) than application:didFinishedLaunchWithOptionsmethod will called.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions != nil)
{
//opened from a push notification when the app is closed
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo != nil)
{
NSLog(#"userInfo->%#",[userInfo objectForKey:#"aps"]);
}
}
else{
//opened app without a push notification.
}
}
I'm new to iPhone development, but managed to receive push notifications in my iOS App. However, when I swipe away the incoming push notification, it just opens the app, but not the related post to the notification.
This is my code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(#"Eine Nachricht ist angekommen, während die App aktiv ist");
NSString* alert = [[userInfo objectForKey:#"aps"] objectForKey:#"id"];
NSLog(#"Nachricht: %#", alert);
//This is to inform about new messages when the app is active
//UIApplicationState state = [[UIApplication sharedApplication] applicationState];
//if (state == UIApplicationStateActive) {
// UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"Neuer Artikel" message:#"Nachricht" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
// [alertView show];
// }
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Device Token=%#", deviceToken);
NSUInteger theCount = [deviceToken length];
NSMutableString *theString = [NSMutableString stringWithCapacity:2 * theCount];
unsigned char const *theBytes = [deviceToken bytes];
for(NSUInteger i = 0; i < theCount; ++i) {
[theString appendFormat:#"%2.2x", theBytes[i]];
}
NSString* url = [NSString stringWithFormat:#"HERE_IS_MY_REGISTERING_URL",theString,theString];
NSLog(#"APNS URL : %#",url);
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(#"Error bei der Registrierung");
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window.frame = [[UIScreen mainScreen] bounds];
[self setApplicationDefaults];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
//This is the start of the push notification settings
[self.window makeKeyAndVisible];
Now, I have no Idea what to put where, to open a related post to a push notification...
What do you expect? From your code, I can not see that you are providing any information about which post you want to be opened. Neither Apple, nor Xcode, or your code will know that by magic.
In your payload for the push notification, you must provide information what post you are referring to, and then read this information in your didReceiveRemoteNotification.
See: "Examples of JSON Payloads" here: Apple Push Notification Service