i added a UILocalNotification with repeat interval of a minute.
how to remove it?
[[UIApplication sharedApplication] cancelAllLocalNotifications];
just copy it under the method didLaunchWithOptions or viewDidLoad or even on your next UILocalNotification code.
- (BOOL)scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
localNotification.soundName = soundfileName != nil ? soundfileName : UILocalNotificationDefaultSoundName;
localNotification.alertLaunchImage = launchImage;
localNotification.userInfo = userInfo;
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.fireDate timeIntervalSinceDate:localNotification.fireDate] == 0 &&
[notification.alertBody isEqualToString:localNotification.alertBody]
) {
return NO;
}
}
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
return YES;
}
- (NSArray *)allLocalNotifications
{
return [[UIApplication sharedApplication] scheduledLocalNotifications];
}
- (void)cancelLocalNotification:(UILocalNotification *)notification
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
- (void)cancelAllLocalNotifications
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
you should make a unique identifier to remove notification, such as alertBody..
then
- (void)cancelLocalNotificationByAlertBody:(NSString *)alertBody
{
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.alertBody isEqual:alertBodyString] ) {
[self cancelLocalNotification:notification];
break;
}
}
}
Try with
notification.repeatInterval = NSCalendarUnit(rawValue: 0)
This code is in Swift. Try with the same thing in objective-c.
Related
After lot of googling and following apple's doc , still I am not able to get action button in remote(push) notification but I am getting it in local notification by following the same code for local notification.
- (void)triggerAndRegisterNotification {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
// create actions
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// create actions
UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:#"com.AG.yes"
title:#"Save"
options:UNNotificationActionOptionForeground];
UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:#"com.AG.no"
title:#"Decline"
options:UNNotificationActionOptionDestructive];
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"com.AG.snooze"
title:#"Snooze"
options:UNNotificationActionOptionDestructive];
NSArray *notificationActions = #[ acceptAction, declineAction, snoozeAction ];
// create a category
UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier actions:notificationActions intentIdentifiers:#[] options:UNNotificationCategoryOptionNone];
NSSet *categories = [NSSet setWithObject:inviteCategory];
// registration
[center setNotificationCategories:categories];
#endif
} else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0")) {
// create actions
UIMutableUserNotificationAction *acceptAction =
[[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = #"com.AG.yes";
acceptAction.title = #"Accept";
acceptAction.activationMode =
UIUserNotificationActivationModeBackground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO; //If YES requies
passcode, but does not unlock the device
UIMutableUserNotificationAction *declineAction =
[[UIMutableUserNotificationAction alloc] init];
declineAction.identifier = #"com.AG.no";
acceptAction.title = #"Decline";
acceptAction.activationMode =
UIUserNotificationActivationModeBackground;
declineAction.destructive = YES;
acceptAction.authenticationRequired = NO;
UIMutableUserNotificationAction *snoozeAction =
[[UIMutableUserNotificationAction alloc] init];
snoozeAction.identifier = #"com.AG.snooze";
acceptAction.title = #"Snooze";
snoozeAction.activationMode =
UIUserNotificationActivationModeBackground;
snoozeAction.destructive = YES;
snoozeAction.authenticationRequired = NO;
// create a category
UIMutableUserNotificationCategory *inviteCategory =
[[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = CYLInviteCategoryIdentifier;
NSArray *notificationActions = #[ acceptAction, declineAction,
snoozeAction ];
[inviteCategory setActions:notificationActions
forContext:UIUserNotificationActionContextDefault];
[inviteCategory setActions:notificationActions
forContext:UIUserNotificationActionContextMinimal];
// registration
NSSet *categories = [NSSet setWithObject:inviteCategory];
UIUserNotificationType types = UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication]
registerUserNotificationSettings:settings];
}
/// 2. request authorization for localNotification
[self registerNotificationSettingsCompletionHandler:^(BOOL
granted,
NSError * _Nullable error) {
if (granted) {
NSLog(#"request authorization succeeded!");
[[UIApplication sharedApplication]
registerForRemoteNotifications];
}
}];
**COMMENTED CODE FOR LOCAL NOTIFICATION**
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
// #if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
// Deliver the notification at 08:30 everyday
// NSDateComponents *dateComponents = [[NSDateComponents
alloc] init];
// dateComponents.hour = 8;
// dateComponents.minute = 30;
// UNCalendarNotificationTrigger *trigger =
// [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:dateComponents
repeats:YES];
// UNMutableNotificationContent *content =
[[UNMutableNotificationContent alloc] init];
// content.title = [NSString
localizedUserNotificationStringForKey:#"AG said:"
arguments:nil];
// content.body = [NSString
localizedUserNotificationStringForKey:#"Hello Tom!Get up,
let's play with Jerry!" arguments:nil];
// content.sound = [UNNotificationSound
defaultSound];
// content.categoryIdentifier =
CYLInviteCategoryIdentifier;
/// 4. update application icon badge number
// content.badge = #([[UIApplication sharedApplication]
applicationIconBadgeNumber] + 1);
// content.launchImageName = #"any string is ok,such as
微博#iOS程序犭袁";
// Deliver the notification in five seconds.
//*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'time interval
must be at least 60 if repeating'
// UNTimeIntervalNotificationTrigger *trigger =
[UNTimeIntervalNotificationTrigger
// triggerWithTimeInterval:60.0f repeats:YES];
// UNNotificationRequest *request = [
UNNotificationRequest
requestWithIdentifier:#"FiveSecond"
// content:content trigger:trigger];
// UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
/// 3. schedule localNotification,The delegate must be set before
the application returns from
applicationDidFinishLaunching:.
// center.delegate = self;
// [center addNotificationRequest:request
withCompletionHandler:^(NSError * _Nullable error) {
// if (!error) {
// NSLog(#"add NotificationRequest succeeded!");
// }
// }];
//#endif
// } else {
/// 3. schedule localNotification
// UILocalNotification *localNotification =
[[UILocalNotification alloc] init];
// localNotification.fireDate = [NSDate
dateWithTimeIntervalSinceNow:5.f];
// localNotification.alertTitle = #"AG said:";
// localNotification.alertBody = #"Hello Tom!Get up,
let's play with Jerry!";
// localNotification.alertAction = #"play with Jerry";
//Identifies the image used as the launch image when the user
taps (or slides) the action button (or slider).
// localNotification.alertLaunchImage =
#"LaunchImage.png";
// localNotification.userInfo = #{ #"CategoryIdentifier"
: CYLInviteCategoryIdentifier };
//
// localNotification.timeZone = [NSTimeZone
defaultTimeZone];
//repeat evey minute, 0 means don't repeat
// localNotification.repeatInterval = NSCalendarUnitMinute;
/// 4. update application icon badge number
// localNotification.applicationIconBadgeNumber =
[[UIApplication sharedApplication]
applicationIconBadgeNumber] + 1;
// [[UIApplication sharedApplication]
scheduleLocalNotification:localNotification];
//
// }
}
/// 3. THIS IS THE METHOD TO AUTHORIZE THE NOTIFICATION
- (void)registerNotificationSettingsCompletionHandler:(void (^)(BOOL
granted, NSError *__nullable error))completionHandler; {
/// 2. request authorization for localNotification
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
[center requestAuthorizationWithOptions:
(UNAuthorizationOptionBadge | UNAuthorizationOptionSound
| UNAuthorizationOptionAlert)
completionHandler:completionHandler];
#endif
} else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0"))
{
// UIUserNotificationSettings
*userNotificationSettings = [UIUserNotificationSettings
settingsForTypes:(UIUserNotificationTypeAlert |
UIUserNotificationTypeSound |
UIUserNotificationTypeBadge)
//
categories:nil];
// UIApplication *application = [UIApplication
sharedApplication];
// [application
registerUserNotificationSettings:userNotificationSettings];
//FIXME:
// !completionHandler ?: completionHandler(granted, error);
}
}
**AND IN** APPDELEGATE.m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
/// schedule localNotification, the delegate must be set before
// the application returns fromapplicationDidFinishLaunching:.
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
center.delegate = self;
#endif
}
[self triggerAndRegisterNotification];
}
I am using iphone 7 for testing purpose.
Please help me solve this. Thanks in Advance
Payload JSon
aps = {
alert = {
"artist_id" = 16912;
body = "Kurt Rosenwinkel is playing at Joe Henderson Lab at
SFJAZZ Center";
eventid = 149687805;
sound = default;
timestamp = "810b6035-e4d7-4722-81db-7455e81a48fe";
title = "Kurt Rosenwinkel";
tracks = "itunes,spotify";
type = 2;
};
category = "com.wcities.notification";
};
I checked the category identifier which I set in my app is also same as in payload json.
UPDATE
As I debugged and come to the point that from above code I am getting push notification with action buttons but in some where after did finish launching I am changing my windows root view controller to view controller which is a child of IIViewDeckController.
After commenting this line push notification is coming with action buttons. I am totally confused why it is happening because as per my knowledge there should not be any impact on push notifications if I set or present or push any viewcontroller.
please let me know If I am doing any mistakes here. I have shared all code and scenario above.
Thanks
As I am using dockview library so the viewcontrollers which are added in dock view controller had some code related to setting categories as nil.That is the reason due to which I couldn't able to get the action button in remote notification so I remove this extra code and everything is working fine. I am still finding that stupid person who wrote this code. Appretiate the help
in ios 10 notification work with -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
//code
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
}
I want to change the below code to UNUserNotification format.I can"t change it into the correct format. Can any one help me?
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
bool neverRepeats = true;
for(id key in _repeatDays) {
if([[_repeatDays objectForKey:key] boolValue]) {
neverRepeats = false;
localNotification.fireDate = _alarmTime;
localNotification.alertBody = #"Title";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.alertAction = #"I'm up, I'm up!";
localNotification.repeatInterval = NSWeekCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
if(neverRepeats) {
if([_alarmTime earlierDate:today] == today) {
localNotification.fireDate = _alarmTime;
localNotification.alertBody = #"Title";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.alertAction = #"I'm up, I'm up!";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
I have an app in iOS where I am sending quick surveys to the users. I want to make use of the new funcionality in iOS 8 where the user interacts directly on the push notification. The user will receive the survey question and respond.
I know you have to construct your actions and categories when starting the app. I have written my code and have been able to successfully perform this so far.
Now, the thing is that the text on the action button will change based on the survey question. I am including the keys and text for the action buttons on the JSON I am sending, but I haven't been able to change the action button titles when receiving the notification.
Is there a way to do this? Here is my code:
I define global variables:
//This will help configure the interactive notifications, so that the user can reply to push notification from out of the app
NSString * const notificationCategoryIdent = #"SURVEY";
NSString * const notificationActionPositiveButton = #"POSITIVE_BUTTON";
NSString * const notificationActionNegativeButton = #"NEGATIVE_BUTTON";
In my AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if(pushNotificationPayload) {
urlPushData2 = #"Application was closed";
[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:pushNotificationPayload];
}
//Registrar tipos de aviso para Push Notifications
//if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)]){
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0){ //Before iOS 8
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)];
}
else {
// define notification actions (In case of categorized remote push notifications)
positiveButton = [[UIMutableUserNotificationAction alloc] init];
[positiveButton setActivationMode:UIUserNotificationActivationModeForeground];
[positiveButton setTitle:notificationActionPositiveButton];
[positiveButton setIdentifier:notificationActionPositiveButton];
[positiveButton setDestructive:NO];
// this action wil be executed without necessity of passcode authentication (if locked)
[positiveButton setAuthenticationRequired:NO];
negativeButton = [[UIMutableUserNotificationAction alloc] init];
[negativeButton setActivationMode:UIUserNotificationActivationModeForeground];
[negativeButton setTitle:notificationActionNegativeButton];
[negativeButton setIdentifier:notificationActionNegativeButton];
[negativeButton setDestructive:NO];
// this action wil be executed without necessity of passcode authentication (if locked)
[negativeButton setAuthenticationRequired:NO];
// define Categories (In case of categorized remote push notifications)
UIMutableUserNotificationCategory *actionCategory;
actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:notificationCategoryIdent];
[actionCategory setActions:#[positiveButton, negativeButton]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
//Boolean value for temporary app interruptions
temporaryInactivity = FALSE;
return YES;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
//NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
self.mainUrl = [userInfo valueForKey:#"url"];
urlPushData = [NSString stringWithFormat:#"%#", mainUrl];
//NSLog(#"urlPushData: %#",urlPushData);
self.mainUrl2 = [userInfo valueForKey:#"url2"];
urlPushData2 = [NSString stringWithFormat:#"%#", mainUrl2];
//NSLog(#"urlPushData2: %#",urlPushData2);
NSString *category = [apsInfo objectForKey:#"category"];
NSLog(#"category: %#", category);
if ([category isEqualToString:notificationCategoryIdent]) {
NSLog(#"button1: %#", [apsInfo objectForKey:#"positiveButton"]);
NSLog(#"button2: %#", [apsInfo objectForKey:#"negativeButton"]);
NSString *stringPositiveButton = [apsInfo objectForKey:#"positiveButton"];
NSString *stringNegativeButton = [apsInfo objectForKey:#"negativeButton"];
[positiveButton setTitle:stringPositiveButton];
[negativeButton setTitle:stringNegativeButton];
}
else {
if (![urlPushData2 isEqualToString:#"Application was closed"]) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
[[NSUserDefaults standardUserDefaults] setObject:urlPushData2 forKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] setObject:alert forKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
if (NSClassFromString(#"UIAlertController")) {
//make and use a UIAlertController
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:#"%#",appNameLink]
message:[NSString stringWithFormat:#"Has recibido una nueva nota: %#. ¿Deseas verla?",alert]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *Cancel = [UIAlertAction actionWithTitle:#"No"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
];
UIAlertAction *OK = [UIAlertAction actionWithTitle:#"Sí"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
self.url = [[NSUserDefaults standardUserDefaults] objectForKey:#"pushNotificationURL"];
self.urlName = [[NSUserDefaults standardUserDefaults] objectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self setupNavigationControllerApp];
}
];
[alertView addAction:Cancel];
[alertView addAction:OK];
[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertView animated:YES completion:nil];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:#"%#",appNameLink] message:[NSString stringWithFormat:#"Has recibido una nueva nota: %#. ¿Deseas verla?",alert] delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Sí", nil];
[alertView show];
}
} else {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
//self.url = [[NSUserDefaults standardUserDefaults]objectForKey:#"pushNotificationURL"];
self.url = urlPushData2;
self.urlName = alert;
[self setupNavigationControllerApp];
}
}
}
- (void) application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:notificationActionPositiveButton]) {
//Testing the action button
self.url = #"http://www.google.com";
self.urlName = #"hello";
[self setupNavigationControllerApp];
}
else if ([identifier isEqualToString:notificationActionNegativeButton]) {
//Testing the action button
self.url = #"http://www.yahoo.com";
self.urlName = #"goodbye";
[self setupNavigationControllerApp];
}
// Must be called when finished
completionHandler();
}
And this is my JSON:
{"aps":
{"alert":"Who's your favorite pop singer?",
"badge":1,
"sound":"default",
"category":"SURVEY",
"positiveButton":"Katy Perry",
"negativeButton":"Miley Cyrus"
},
"url":"http://www.pretechmobile.com",
"url2":"http://goo.gl/U9p1y"
}
I am sorry, but you cannot change the title of the buttons dynamically. They are tied to the category in which they are stored when you register for notifications.
A possible workaround could be to present the two options in the text of the message labeled with an 'A' and a 'B' and have your buttons with titles 'Option A' and 'Option B'. Something like this:
---------------------------------
|Who's your favorite pop singer?|
|A: Katy Perry B: Miley Cyrus|
---------------------------------
| Option A | Option B |
---------------------------------
Also, If you have yes/no questions, you can create a category for them with the options 'Yes' and 'No' and label your notifications with this category.
I hope this helps a bit.
I am getting push notification from server but my postNotification is not being called. It is correctly entering in if statement which states that type == 1. All the user defaults are correctly stored but the notification is not being called. I put the break point as well as an alert in the function of view controller which is called by the post notification. But it never being called. Here is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if(launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSString *type = [dictionary objectForKey:#"type"];
if([[NSString stringWithFormat:#"%#",type]integerValue]==1)
{
[[NSUserDefaults standardUserDefaults]setObject:[[dictionary objectForKey:#"aps"] valueForKey:#"alert"] forKey:#"message"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"senderid"] forKey:#"senderID"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"sendername"] forKey:#"sendername"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"userimage"] forKey:#"pushImage"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(#"message is %#",[[dictionary objectForKey:#"aps"] valueForKey:#"alert"]);
NSLog(#"senderID is %#",[dictionary objectForKey:#"senderid"]);
NSLog(#"sender name is %#",[dictionary objectForKey:#"sendername"]);
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushNotification" object:nil userInfo:launchOptions];
}
}
#ifdef __IPHONE_8_0
if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
#endif
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeNewsstandContentAvailability;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
application.applicationIconBadgeNumber=0;
[UIApplication sharedApplication].statusBarHidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible=FALSE;
return YES;
}
Find the answer of my own question. Here is the code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[self window] setBackgroundColor:[UIColor whiteColor]];
[FBLoginView class];
self.mainNavigationController = (UINavigationController*)self.window.rootViewController;
if(launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSString *type = [NSString stringWithFormat:#"%#",[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"type"]];
NSLog(#"type is %#",type);
if ([type isEqualToString:#"0"]) // 0 means NOW
{
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"yadda_sub_type"] forKey:kYaddaSubType_Push];
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"user_id"] forKey:kYaddaUserID_Push];
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"yadda_id"] forKey:kYaddaID_Push];
ReciversSideVC *reciverControoler = [[ReciversSideVC alloc]init];
[reciverControoler.navigationController setNavigationBarHidden:YES];
[reciverControoler.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:reciverControoler animated:NO];
}
else if ([type isEqualToString:#"1"]) // 1 means LATER
{
if (isCalendarScreenOpen==YES)
{
CalendarVC *calendar = [[CalendarVC alloc]init];
[calendar.navigationController setNavigationBarHidden:YES];
[calendar.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:calendar animated:NO];
}
}
else if ([type isEqualToString:#"2"]) // 2 means Remind me
{
LandingPageVC *landing = [[LandingPageVC alloc]init];
[landing.navigationController setNavigationBarHidden:YES];
[landing.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:landing animated:NO];
}
else if ([type isEqualToString:#"3"]) // 3 means Reply
{
LandingPageVC *landing = [[LandingPageVC alloc]init];
[landing.navigationController setNavigationBarHidden:YES];
[landing.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:landing animated:NO];
}
else if ([type isEqualToString:#"4"]) // 4 means Contacts
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"flag_CallAPI"];
[[NSUserDefaults standardUserDefaults]synchronize];
ContactDetailVC *contactDetails = [[ContactDetailVC alloc]init];
contactDetails.userID = [[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"user_id"];
contactDetails.phoneNumberFromServer = [[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"phone_number"];
[contactDetails.navigationController setNavigationBarHidden:YES];
[contactDetails.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:contactDetails animated:NO];
}
}
}
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif != nil)
{
NSDictionary *NotificationValue = [localNotif.userInfo objectForKey:#"localPushNotification"];
if (NotificationValue != nil)
{
NSLog(#"Run with notification value: %#", NotificationValue);
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"yadda_sub_type"] forKey:kYaddaSubType_Push];
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"user_id"] forKey:kYaddaUserID_Push];
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"yadda_id"] forKey:kYaddaID_Push];
ReciversSideVC *reciverControoler = [[ReciversSideVC alloc]init];
[AppDelegateClass.mainNavigationController pushViewController:reciverControoler animated:NO];
}
}
if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeNewsstandContentAvailability;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
application.applicationIconBadgeNumber=0;
[UIApplication sharedApplication].statusBarHidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible=FALSE;
return YES;
}
I have a universal app. I'm using separate xibs for the portrait and landscape views. I have the app detecting the orientation and changing the value of a BOOL to true when I'm in landscape. I want to know how to load my landscape xib when that BOOL is true. I've tried several different methods to achieve this, but nothing has worked. Any input on this matter would be most appreciated. I can update this post to include any code snippets necessary. Thanks in advance.
edit: I want to do all of this in one ViewController class, and only for the iPad... not the iPhone. I have all that part worked out. I just need to load the landscape xib.
edit: In my viewDidLoad I'm doing this:
if (userDevice.orientation == UIDeviceOrientationLandscapeLeft || userDevice.orientation == UIDeviceOrientationLandscapeRight) {
landscape = YES;
}
Here's my main view controller .m:
#implementation PassportAmericaViewController
#synthesize browseViewButton, webView, mainView, lblMemberName, menuOpen, internetActive, hostActive, isUsingiPad, portrait, landscape;
- (void)viewDidLoad {
menuOpen = NO;
UIDevice* userDevice = [UIDevice currentDevice];
if (userDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
isUsingiPad = YES;
}
if (isUsingiPad)
if (userDevice.orientation == UIDeviceOrientationLandscapeLeft || userDevice.orientation == UIDeviceOrientationLandscapeRight) {
landscape = YES;
}
[self checkForKey];
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:YES];
}
-(void)viewWillAppear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:YES];
}
-(void) checkForKey{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int regCheck = [defaults integerForKey:#"registration"];
if (isUsingiPad) {
if (regCheck == 0) {
RegistrationViewController *regView = [[RegistrationViewController alloc]
initWithNibName:#"RegistrationView-iPad" bundle:[NSBundle mainBundle]];
regView.isUsingiPad = YES;
[self.navigationController pushViewController:regView animated:YES];
}else if (regCheck == 1) {
#try {
NSString *mbrFirstName = [defaults objectForKey:#"firstName"];
NSString *mbrLastName = [defaults objectForKey:#"lastName"];
NSMutableString *name = [[NSMutableString alloc] initWithString:mbrFirstName];
[name appendString:#" "];
[name appendString:mbrLastName];
lblMemberName.text = name;
}
#catch (NSException *exception) {
}
}
}else{
if (regCheck == 0) {
RegistrationViewController *regView = [[RegistrationViewController alloc]
initWithNibName:#"RegistrationView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:regView animated:YES];
}else if (regCheck == 1) {
#try {
NSString *mbrFirstName = [defaults objectForKey:#"firstName"];
NSString *mbrLastName = [defaults objectForKey:#"lastName"];
NSMutableString *name = [[NSMutableString alloc] initWithString:mbrFirstName];
[name appendString:#" "];
[name appendString:mbrLastName];
lblMemberName.text = name;
}
#catch (NSException *exception) {
}
}
}
}
-(IBAction) openBrowseView{
if (isUsingiPad && landscape) {
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView-iPadLandscape" bundle:[NSBundle mainBundle]];
browseView.isUsingiPad = YES;
[self.navigationController pushViewController:browseView animated:YES];
}else if (isUsingiPad){
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView-iPad" bundle:[NSBundle mainBundle]];
browseView.isUsingiPad = YES;
[self.navigationController pushViewController:browseView animated:YES];
}else{
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:browseView animated:YES];
}
}
-(IBAction) openViewMore{
if (isUsingiPad) {
ViewMoreViewController *viewMoreView = [[ViewMoreViewController alloc]
initWithNibName:#"ViewMoreView-iPad" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewMoreView animated:YES];
viewMoreView.isUsingiPad = YES;
}else{
ViewMoreViewController *viewMoreView = [[ViewMoreViewController alloc]
initWithNibName:#"ViewMoreView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewMoreView animated:YES];
}
}
-(IBAction) callTollFree:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"tel:8002837183"]];
}
-(IBAction)clickToJoin:(id)sender {
if (isUsingiPad) {
webView = [[WebViewController alloc]
initWithNibName:#"WebView-iPad" bundle:[NSBundle mainBundle]];
webView.url=#"http://www.passport-america.com/Members/JoinRenew.aspx";
[self.navigationController pushViewController:webView animated:YES];
webView.isUsingiPad = YES;
}else {
webView = [[WebViewController alloc]
initWithNibName:#"WebView" bundle:[NSBundle mainBundle]];
webView.url=#"http://www.passport-america.com/Members/JoinRenew.aspx";
[self.navigationController pushViewController:webView animated:YES];
}
}
-(IBAction) iPadContactUs:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: #"mailto:info#passport-america.com"]];
}
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:#"slideMenu"]){
UIView *sq = (__bridge UIView *) context;
[sq removeFromSuperview];
}
}
-(void) positionViews {
if (isUsingiPad) {
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
PassportAmericaViewController *homeView2 = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController-iPad" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView2 animated:YES];
homeView2.isUsingiPad = YES;
homeView2.portrait = YES;
homeView2.landscape = NO;
}else{
PassportAmericaViewController *homeView2 = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController-iPadLandscape" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView2 animated:YES];
homeView2.isUsingiPad = YES;
homeView2.portrait = NO;
homeView2.landscape = YES;
}
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (isUsingiPad) {
return YES;
}else{
// Return YES for supported orientations
return NO;
}
}
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration {
if (isUsingiPad) {
[self positionViews];
}else{
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
Edit
It looks like you need to do your work here
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
RegistrationViewController *regView = [[RegistrationViewController alloc] initWithNibName:nibName bundle:[NSBundle mainBundle]];
I'm not sure where you are getting stuck...
- (id)init;
{
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
self = [super initWithNibName:nibName bundle:nil];
if (self) {
// any other init stuff
}
return self;
}
or if you prefer to name the nib when you instantiate
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
MyViewController *viewController = [[MyViewController alloc] initWithNibName:nibName bundle:nil];