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
Related
The iOS app I have been hired to build uses Batch and Rover. While I have had success in getting Batch to display an incoming notification, Rover is not even attempting to connect. I've been trying to figure this problem out for a few hours now. Here is my AppDelegate:
#import Batch;
#import Rover;
#import "app_appDelegate.h"
#import "BT_loading.h"
#implementation app_appDelegate
//didFinishLaunchingWithOptions...
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[BT_debugger showIt:self message:[NSString stringWithFormat:#"didFinishLaunchingWithOptions (iOS)%#", #""]];
[Batch startWithAPIKey:#"_removed_"];
[BatchPush registerForRemoteNotifications];
[Rover setupWithApplicationToken:#"_removed_"];
[Rover registerForNotifications];
[Rover startMonitoring];
NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
// notificationPayload = #{#"nickname":#"Wine List 1"};
[self appOpenDeepLink:notificationPayload];
// Register for Push Notitications, if running iOS 8
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
} else {
// Register for Push Notifications before iOS 8
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound)];
if (application.applicationState != UIApplicationStateBackground) {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced
// in iOS 7). In that case, we skip tracking here to avoid double
// counting the app-open.
BOOL preBackgroundPush = ![application respondsToSelector:#selector(backgroundRefreshStatus)];
BOOL oldPushHandlerOnly = ![self respondsToSelector:#selector(application:didReceiveRemoteNotification:fetchCompletionHandler: self: showDeepLinkScreen:userInfo:)];
BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
//[PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
}
}
}
NSLog(#"Notification Payload: %#", notificationPayload);
//hide status bar on launch...
[[UIApplication sharedApplication] setStatusBarHidden:TRUE withAnimation:UIStatusBarAnimationNone];
//setup the window on launch...
[self setWindow:[[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]];
[self.window setBackgroundColor:[BT_color getColorFromHexString:#"#FFFFFF"]];
//load initial storyboard, "BT_loading"...
UIStoryboard *launchStoryboard = [UIStoryboard storyboardWithName:#"BT_loading" bundle:nil];
BT_viewController *launchViewController = [launchStoryboard instantiateViewControllerWithIdentifier:#"BT_loading"];
//set the rootViewController on the window to the BT_loading storyboard...
self.window.rootViewController = launchViewController;
[self.window makeKeyAndVisible];
//return...
return TRUE;
}
- (void) appOpenDeepLink:(NSDictionary *) notificationPayload{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"screenNickname"];
if(notificationPayload[#"nickname"]){
[[NSUserDefaults standardUserDefaults] setObject:notificationPayload[#"nickname"] forKey:#"screenNickname"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
//when app becomes active again
- (void)applicationDidBecomeActive:(UIApplication *)application{
//make sure we have an app...
if([self rootApp] == nil){
[BT_debugger showIt:self message:[NSString stringWithFormat:#"applicationDidBecomeActive rootApp not available yet (iOS).%#", #""]];
}else{
[BT_debugger showIt:self message:[NSString stringWithFormat:#"applicationDidBecomeActive (iOS)%#", #""]];
//flag as visible...
[self setUiIsVisible:TRUE];
//report to cloud (not all apps do this, dataURL and reportToCloudURL required)...
if([[self.rootApp dataURL] length] > 1 && [[self.rootApp reportToCloudURL] length] > 1){
if(![self isRefreshing]){
[self reportToCloud];
}
}
//if we have a location manager...
if([self rootLocationManager] != nil){
[self.rootLocationManager setUpdateCount:0];
[self.rootLocationManager.locationManager startUpdatingLocation];
}
}
}
//promptforPushNotificationsAfterDelay...
-(void)promptforPushNotificationsAfterDelay{
[BT_debugger showIt:self message:[NSString stringWithFormat:#"promptforPushNotificationsAfterDelay%#", #""]];
if([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)]){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
//didRegisterForRemoteNotificationsWithDeviceToken...
-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
[Rover didRegisterForRemoteNotificationWithDeviceToken:deviceToken];
[BT_debugger showIt:self theMessage:[NSString stringWithFormat:#"didRegisterForRemoteNotificationsWithDeviceToken (iOS): Device Token: %#", deviceToken]];
//if we have a token, and a register it...
if([deviceToken length] > 1 && [[self.rootApp registerForPushURL] length] > 1){
//clean up token...
NSString *useToken = [NSString stringWithFormat:#"%#", deviceToken];
useToken = [useToken stringByReplacingOccurrencesOfString:#"<"withString:#""];
useToken = [useToken stringByReplacingOccurrencesOfString:#">"withString:#""];
useToken = [useToken stringByReplacingOccurrencesOfString:#" "withString:#""];
//save it for next time...
[BT_strings setPrefString:#"lastDeviceToken" valueOfPref:useToken];
//append deviceToken and deviceType to end of URL...
NSString *useURL = [[self.rootApp registerForPushURL] stringByAppendingString:[NSString stringWithFormat:#"&deviceType=%#", #"ios"]];
useURL = [useURL stringByAppendingString:[NSString stringWithFormat:#"&deviceToken=%#", useToken]];
//append currentMode ("Live" or "Design") to end of URL...
useURL = [useURL stringByAppendingString:[NSString stringWithFormat:#"¤tMode=%#", [self currentMode]]];
//merge environment variables in URL...
useURL = [BT_strings mergeBTVariablesInString:useURL];
//escape the URL...
NSString *escapedUrl = [useURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//tell the BT_device to register on the server (the device class makes the URL request)...
[appDelegate.rootDevice registerForPushNotifications:escapedUrl];
}
}
//didFailToRegisterForRemoteNotificationsWithError...
-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
[BT_debugger showIt:self theMessage:[NSString stringWithFormat:#"didFailToRegisterForRemoteNotificationsWithError (iOS): ERROR: %#", error]];
}
//didReceiveRemoteNotification..
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
[BT_debugger showIt:self theMessage:[NSString stringWithFormat:#"didReceiveRemoteNotification (iOS)%#", #""]];
//NSLog(#"Message ID: %#", userInfo);
//NSLog(#"%#", userInfo);
//(void)[Rover didReceiveRemoteNotification:userInfo fetchCompletionHandler:nil];
//don't do anything if the app is not in the foreground. iOS handles inbound APNS message when app is in the background...
if(application.applicationState == UIApplicationStateActive){
NSString *alertMsg;
NSString *badge;
NSString *sound;
//alert message...
if([[userInfo objectForKey:#"aps"] objectForKey:#"alert"] != NULL){
alertMsg = [[userInfo objectForKey:#"aps"] objectForKey:#"alert"];
}
//badge...
if([[userInfo objectForKey:#"aps"] objectForKey:#"badge"] != NULL){
badge = [[userInfo objectForKey:#"aps"] objectForKey:#"badge"];
}
//sound...
if([[userInfo objectForKey:#"aps"] objectForKey:#"sound"] != NULL){
sound = [[userInfo objectForKey:#"aps"] objectForKey:#"sound"];
}
//if we have a sound...
if([sound length] > 1){
[self performSelector:#selector(playSoundFromPushMessage:) withObject:sound afterDelay:.1];
}
//show messsage...
//UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
//UIAlertAction* MyAlert = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *alertTag)
// {
// OK button tappped.
//[self dismissViewControllerAnimated:YES completion:^{
//}];
// }];
// [alert addAction:MyAlert];
//[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alert animated:YES completion:nil];
//show messsage...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:alertMsg delegate:nil cancelButtonTitle:NSLocalizedString(#"ok", "OK") otherButtonTitles:nil];
[alert show];
////WATCH
}//in foreground...
}
//playSoundFromPushMessage...
-(void)playSoundFromPushMessage:(NSString *)soundEffectFileName{
[BT_debugger showIt:self theMessage:[NSString stringWithFormat:#"playSoundFromPushMessage: %#", soundEffectFileName]];
NSString *theFileName = soundEffectFileName;
if([BT_fileManager doesFileExistInBundle:theFileName]){
NSURL *soundFileUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], theFileName]];
NSError *error;
AVAudioPlayer *tmpPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileUrl error:&error];
if(!error){
[tmpPlayer setNumberOfLoops:0];
[tmpPlayer prepareToPlay];
[tmpPlayer play];
}else{
[BT_debugger showIt:self theMessage:[NSString stringWithFormat:#"didReceiveRemoteNotification soundEffectPlayer ERROR: %#", [error description]]];
}
}
}
//playSoundEffect...
-(void)playSoundEffect:(NSString *)theFileName{
[BT_debugger showIt:self message:[NSString stringWithFormat:#"playSoundEffect %#", theFileName]];
if([theFileName length] > 3){
if([self.rootSoundEffectPlayer.soundEffectNames containsObject:theFileName]){
int playerIndex = (int)[self.rootSoundEffectPlayer.soundEffectNames indexOfObject:theFileName];
AVAudioPlayer *tmpPlayer = (AVAudioPlayer *)[self.rootSoundEffectPlayer.soundEffectPlayers objectAtIndex:playerIndex];
if(tmpPlayer){
[tmpPlayer play];
}
}else{
[BT_debugger showIt:self message:[NSString stringWithFormat:#"playSoundInBundle:ERROR. This sound effect is not included in the list of available sounds: %#", theFileName]];
}
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(#"Message ID: %#", userInfo);
NSLog(#"%#", userInfo);
(void)[Rover didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
#end
I have been going off the instruction created by the Rover developers at: https://github.com/RoverPlatform/rover-ios
I'm probably missing something simple but guidance would definitely be appreciated.
My logcat's responses to Rover:
Rover [4] - [LocationManager.swift.startMonitoring() - Line 76] => Monitoring started.
Rover [4] - [EventOperation.swift.execute() - Line 106] => Submitting event - applicationOpen(2018-02-28 07:46:02 +0000)
Rover [4] - [BluetoothStatusOperation.swift.execute() - Line 34] => Checking Bluetooth status
Rover [4] - [BluetoothStatusOperation.swift.centralManagerDidUpdateState - Line 48] => Determined Bluetooth status - true
Rover [4] - [LocationManager.swift.locationManager(_:didUpdateLocations:) - Line 114] => Received location update.
Rover [0] - [NetworkOperation.swift.execute() - Line 108] => Client error
Rover [4] - [EventOperation.swift.execute() - Line 106] => Submitting event
Rover [0] - [NetworkOperation.swift.execute() - Line 108] => Client error
2018-02-28 02:46:03.792824-0500 app[1540:560757] [CoreBluetooth] XPC connection invalid
If you put a breakpoint on the [Rover startMonitoring]; what happens?
Does rover require you to pass it your APNS token to work?
after iOS 9, I used to check if my app had connection with my server with the next part of code, and If there is no response, I asked user to activate wifi, etc.
Alert which show the dialog:
#pragma mark - SHOW ALERTVIEW FOR IOS 7 or less AND IOS 8
-(void) alertNoInternet:(NSString*)alertTitle withMessage:(NSString *)alertMessage{
NSString *alert3gButtonText = #"Mobile Data";
NSString *alertWifiButtonText = #"WIFI";
NSString *alertCancelButtonText = #"Cancel";
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( NSFoundationVersionNumber_iOS_8_0 ) ) {
NSLog(#"SQA: iOS 8 dialog process");
/*id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = [((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];
}*/
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleActionSheet];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *action3g = [UIAlertAction actionWithTitle:alert3gButtonText
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL *urlCellular = [NSURL URLWithString:#"prefs:root=General&path=USAGE/CELLULAR_USAGE"];
if([[UIApplication sharedApplication] canOpenURL:urlCellular]) {
[[UIApplication sharedApplication] openURL:urlCellular];
}
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionWifi = [UIAlertAction actionWithTitle:alertWifiButtonText
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL *urlWifi = [NSURL URLWithString:#"prefs:root=WIFI"];
if ([[UIApplication sharedApplication] canOpenURL:urlWifi]) {
[[UIApplication sharedApplication] openURL:urlWifi];
}
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:alertCancelButtonText
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action)
{
[alertController dismissViewControllerAnimated:YES completion:nil];
//home button press programmatically
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:#selector(suspend)];
//wait 2 seconds while app is going background
[NSThread sleepForTimeInterval:2.0];
//exit app when app is in background
exit(0);
}];
//[alertController addAction:action3g];
[alertController addAction:actionWifi];
[alertController addAction:actionCancel];
[self presentViewController:alertController animated:YES completion:nil];
}
if (SYSTEM_VERSION_LESS_THAN(NSFoundationVersionNumber_iOS_7_0) ) {
NSLog(#"SQA: iOS 7 or less dialog process");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:alertCancelButtonText
otherButtonTitles:alertWifiButtonText, nil];
alertView.tag = TAG_ALERT_NOINTERNET;
[alertView show];
}
}
And this is the source code to check the connection:
- (void)checkInternet:(connection)block
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://www.tempdevserver.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"HEAD";
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 10.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
block([(NSHTTPURLResponse *)response statusCode] == 200);
}];
}
Now, on iOS 9, dialog is always shown, and never let me pass from there.
What has changed?
Here is the perfect solution, might be helpful to you.
**in your Appdelegate.m File**
//Check Internet Plugin
#include<unistd.h>
#include<netdb.h>
/////
#pragma mark Check Internet connection
-(BOOL)checkInternetConnection {
char *hostname;
struct hostent *hostinfo;
hostname = "google.com";
hostinfo = gethostbyname (hostname);
if (hostinfo == NULL)
{
NSLog(#"-> no connection!\n");
return NO;
}
else{
NSLog(#"-> connection established!\n");
return YES;
}
}
Try above code, it is working fine and perfect.
I want to use a UISwitch to enable/disable push notifications. Like in Tweetbot.
Does anyone know how to trigger that?
You can also do it in the following way.
create a IBOutlet for UISwitch
#property (strong, nonatomic) IBOutlet *pushNotificationSwitch;
and in Action method, store the value in NSUserDefaults.
- (IBAction)pushNotificationSwitchChanged:(id)sender
{
NSNumber *switch_value = [NSNumber numberWithBool:[self.pushNotificationSwitch isOn]];
[[NSUserDefaults standardUserDefaults] setObject:switch_value forKey:RECIEVE_APNS];
[[NSUserDefaults standardUserDefaults] synchronize];
}
and check it in viewdidload.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSNumber *sett = [[NSUserDefaults standardUserDefaults] valueForKey:RECIEVE_APNS];
if( [sett boolValue] )
{
[self.pushNotificationSwitch setOn:YES];
}
else{
[self.pushNotificationSwitch setOn:NO];
}
}
and In AppDelegate.m, add the following code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSNumber *sett = [[NSUserDefaults standardUserDefaults] objectForKey:RECIEVE_APNS];
if( [sett boolValue] )
{
int currentBadgeCount = [[NSUserDefaults standardUserDefaults] integerForKey:#"BadgeCount"];
//Set the baadge count on the app icon in the home screen
int badgeValue = [[[userInfo valueForKey:#"aps"] valueForKey:#"badge"] intValue];
[UIApplication sharedApplication].applicationIconBadgeNumber = badgeValue + currentBadgeCount;
[[NSUserDefaults standardUserDefaults] setInteger:badgeValue + currentBadgeCount forKey:#"BadgeCount"];
NSString *alertString = [[userInfo objectForKey:#"aps"] objectForKey:#"alert"];
NSString *playSoundOnAlert = [NSString stringWithFormat:#"%#", [[userInfo objectForKey:#"aps"] objectForKey:#"sound"]];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#",[[NSBundle mainBundle] resourcePath],playSoundOnAlert]];
NSError *error;
if (alertString.length > 0)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"App Name" message:alertString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
[alert show];
}
}
}
enter code here
You can not do that directly from the application. If you want to do this, you need to make the UISwitch send the information to your backend, store this information in your database and stop sending push notifications to this user.
An app registers for Push Notifications (APN) when it first launches. You cannot have it initialize APNs with a switch once it has already launched. You can however code your app that a switch can choose to do "something" with the user interface once a APN is received.
For example, you can have this code:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
// do what you need with the data...
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReceivedNotificationAlert" object:self];
}
You can use your UISwitch to either do something, or not, with the NSNotification "ReceivedNotificationAlert". For example:
if(switchAPNprocess.on){
// process APN
}
else {
// ignore APN
}
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
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...