So I have managed to set up local notification in my app by doing so.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = text;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
notif.soundName = sound;
};
[app scheduleLocalNotification:notif];
}
inside of a method that is called
- (void)createDateNotification:(NSString*) title alertText: (NSString*)text timeToWait: (NSTimeInterval)time soundToPlay: (NSString*)sound;
and when I call that method, The notification runs just like expected. My problem is that in my game I want it to be when the user clickes on the local notification that it will run a method which now just does so
-(void)rewardUser {
NSLog(#"User rewarded")
}
but sometimes it may run a different method and I don't know how do do it. Anything from swift to objective c will be appreciated. Much thanks!
Override - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification in your AppDelegate and do your thing.
I managed to solve it by doing this. When creating the alert, I set the action to a public string in my class which is called action and as #songchenwen mentioned, I overrided the didReceiveLocalNotification to check if the action is equal to a number of variables and if so run a method for each one.
I called the mothod like this setting a string for the action
[self createReminderNotification:#"Give50Coins" messageTitle:#"t" messageBody:#"gfdhgsh" timeToWait:2 soundToPlay:#"audio.wav"];
And in the method I initialised the notification setting all the details.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
action = actionAfterNotifiy;
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = message;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
};
}
[app scheduleLocalNotification: notif];
and in the - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification
I did this,
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if ([action isEqualToString:#"Give50Coins"]) {
NSLog(#"wheyy");
}
else {
//random stuff here
}
}
Related
In my app delegate the method - (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification is never called.
This is how I create the notification:
UILocalNotification *notification = [[UILocalNotification alloc] init];
// set UUID, which we will store in userDefaults for later
NSMutableDictionary *myUserInfo = [[NSMutableDictionary alloc] init];
NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString];
[myUserInfo setValue:uuid forKey:KEY_UUID];
[myUserInfo setValue:#"month" forKey:KEY_UNIT];
[myUserInfo setObject:#YES forKey:KEY_RESCHEDULE];
NSInteger row = [_wurmProphylaxePickerView selectedRowInComponent:0];
switch (row) {
case 0:
[myUserInfo setValue:#2 forKey:KEY_FREQUENCY];
break;
case 1:
[myUserInfo setValue:#4 forKey:KEY_FREQUENCY];
break;
case 2:
[myUserInfo setValue:#6 forKey:KEY_FREQUENCY];
break;
default:
[myUserInfo setValue:#4 forKey:KEY_FREQUENCY];
break;
}
notification.userInfo = myUserInfo;
// calculate date for next notification, depends on the user's selection
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *myComps = [[NSDateComponents alloc] init];
[myComps setMinute:1];
notification.fireDate = [calendar dateByAddingComponents:myComps toDate:today options:0];
notification.timeZone = [NSTimeZone localTimeZone];
notification.alertBody = #"My alertBody";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
And this is in my app delegates, but is never called:
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
NSDictionary *userInfo = notification.userInfo;
BOOL repeat = [[userInfo objectForKey:KEY_RESCHEDULE] boolValue];
if (repeat)
{
NSInteger frequency = (NSInteger)[userInfo objectForKey:KEY_FREQUENCY];
NSString *unit = (NSString *)[userInfo objectForKey:KEY_UNIT];
NSString *uuid = (NSString *)[userInfo objectForKey:KEY_UUID];
// calculate date for next notification
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *myComps = [[NSDateComponents alloc] init];
if ([unit isEqualToString:#"month"]) {
//[myComps setMonth:frequency];
[myComps setMinute:frequency];
} else {
}
// create new notification
UILocalNotification *newNotification = [[UILocalNotification alloc] init];
newNotification.fireDate = [calendar dateByAddingComponents:myComps toDate:today options:0];
newNotification.timeZone = [NSTimeZone localTimeZone];
newNotification.alertAction = notification.alertAction;
newNotification.alertBody = notification.alertBody;
newNotification.userInfo = notification.userInfo;
// schedule it
[[UIApplication sharedApplication] scheduleLocalNotification:newNotification];
}
}
tested on iOS 8, not sure about iOS 7...
If the app is not active when the notification fires, you would handle this in didFinishLaunchingWithOptions as illustrated by this example from the Handling Local and Remote Notifications section of the Local and Push Notifications Programming Guide:
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSString *itemName = [localNotif.userInfo objectForKey:ToDoItemKey];
[viewController displayItem:itemName]; // custom method
app.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1;
}
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
The didReceiveLocalNotification is called if the app was active when the notification fired.
I am using local notifications in my app. It's firing ok, but when I open the app from the notification, I can't access notification's userinfo. This is how I am scheduling the notification:
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.userInfo = #{#"eventId" : eventID};
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.S"];
NSDate *dateStart = [dateFormatter dateFromString: [eventDictionary valueForKey:#"time_start"]];
NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:15];
notification.fireDate = newDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertAction = #"Open";
notification.alertBody = #"Some title";
notification.soundName = UILocalNotificationDefaultSoundName;
//cfilipi: todo: verify if event date is bigger than today
if ([newDate timeIntervalSinceNow] > 0) {
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
This is how I am handling when I open the app from the notification (AppDelegate.m):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey] != nil){
//even when I cast to NSDictionary, it gets other class type (UIConcreteLocalNotification, I can't find any information about this class)
NSDictionary * aPush = (NSDictionary *)[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
[self handleLocalNotification:aPush];
}
}
-(void)handleLocalNotification:(NSDictionary *)localNotification{
NSDictionary *userInfo = [localNotification objectForKey:#"userinfo"];
NSString *eventId = [userInfo objectForKey:#"eventId"];
if ([eventId length] >= 1) {
//I use this key in some parts of my code
[[NSUserDefaults standardUserDefaults] setObject:eventId forKey:#"eventId"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
And this is what I get from LLDB when I am debugging didFinishLaunchingWithOptions:
(lldb) po aPush
<UIConcreteLocalNotification: 0x145b2ba0>{fire date = quinta-feira, 18 de dezembro de 2014 08:47:13 Horário de Verão de Brasília, time zone = America/Sao_Paulo (BRST) offset -7200 (Daylight), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = (null), user info = {
eventId = 21;
}}
My question is: what am I doing wrong? Is there any way to convert this UIConcreteLocalNotification to NSDictionary? I have tried to convert it to UILocalNotification too, but I had no success.
Regards!
Do like this and it will work fine:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if ( notification != nil )
{
[self handleLocalNotification:[notification userInfo]];
}
}
You have not implemented
-(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
Implement this method and try.
I am making a timer app. The user sets the time and the app counts down from there. I have added a UILocalNotification, so that it pops up even when you aren't in the app to tell you the timer has finished:
IN MY VIEW CONTROLLER:
- (void)setupLocalNotifications {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
totalSeconds = (setHour * 60 * 60) + (setMinute * 60) + (setSecond);
NSDate *now = [NSDate date];
NSDate *dateToFire = [now dateByAddingTimeInterval:totalSeconds];
localNotification.fireDate = dateToFire;
localNotification.alertBody = #"Timer Done";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1; // increment
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:#"Object 1", #"Key 1", #"Object 2", #"Key 2", nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
IN MY APPDELEGATE:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.;
ScrollViewController *sv = [[ScrollViewController alloc] init];
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
[self showAlarm:notification.alertBody];
NSLog(#"AppDelegate didFinishLaunchingWithOptions");
application.applicationIconBadgeNumber = 0;
}
self.window.rootViewController = sv; // Make tab bar controller the root view controller
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[self showAlarm:notification.alertBody];
application.applicationIconBadgeNumber = 0;
NSLog(#"AppDelegate didReceiveLocalNotification %#", notification.userInfo);
}
- (void)showAlarm:(NSString *)text {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Timer"
message:text
delegate:self
cancelButtonTitle:#"Stop Timer"
otherButtonTitles:nil];
[alertView show];
}
What happens is, I set a UILocalNotification to go off after the user-defined number of seconds has passed. However, my app allows you to pause the timer. When paused, the UILocalNotification will carry on, and go off after the seconds have passed. Is there any way to pause the local notification?
A local notification cannot be paused. If the timer is paused in your application,
you should cancel the notification, and create/schedule a new one if the timer
is resumed.
I want to cancel a UILocalnotification , when i cancel notification still the notification is being fired . I wanted to know do i have to call any delegate method in appdelegate to cancel notification .the code which i am using is executing correctly .but the notification is getting fired .
Should i use NSNotification center which has removeObserver method to cancel uilocalnotification.
Does UILocalnotification fires notification from the app or from the device.
UPDATE - This is how i am scheduling my notification
-(UILocalNotification *)scheduleNotification :(int)remedyID
{
NSString *descriptionBody;
NSInteger frequency;
UILocalNotification *notif = [[UILocalNotification alloc] init];
NSLog(#"%d",remedyID);
descriptionBody =[[self remedyDetailsForRemedyID:remedyID] objectForKey:#"RemedyTxtDic"];
frequency = [[[self remedyDetailsForRemedyID:remedyID] objectForKey:#"RemedyFrequency"]intValue];
NSArray *notificationFireDates = [self fireDatesForFrequency:frequency];
for (NSDate *fireDate in notificationFireDates)
{
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = NSDayCalendarUnit;
notif.alertBody = [NSString stringWithString:descriptionBody];
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
notif.fireDate = fireDate;
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:notif.alertBody, #"kRemindMeNotificationDataKey", [NSNumber numberWithInt:remedyID],kRemindMeNotificationRemedyIDKey,
nil];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
return notif;
}
Cancelling notification
- (void)cancelNotification:(int)remedyId
{
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
NSLog(#"Cancelling... Before %d",[[[UIApplication sharedApplication]scheduledLocalNotifications]count]);
for (UILocalNotification *notification in notifications)
{
int notifRemedyId = [[notification.userInfo objectForKey:#"kRemindMeNotificationRemedyIDKey"]intValue];
NSLog(#"remedyID : %d",remedyId);
NSLog(#"notifyId : %d",notifRemedyId);
if (remedyId == notifRemedyId) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
NSLog(#"Cancelling... After %d",[[[UIApplication sharedApplication]scheduledLocalNotifications]count]);
}
NSNotification center which has removeObserver method to cancel uilocalnotification.
NSNotificationCenter has nothing to do with UILocalNotification. I'm sorry that they both use "notification" somewhere in their names, but that is just coincidence really.
scheduledLocalNotifications will give you the list of all scheduled notifications and use
- (void)cancelLocalNotification:(UILocalNotification *)notification
or you can cancel them all using:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Edit :
NSString *notifRemedyId = #"notifRemedyId";
UILocalNotification *localnotif=[[UILocalNotification alloc]init];
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:#"kRemindMeNotificationRemedyIDKey", kRemindMeNotificationRemedyIDKey,YOUR_REMEDYID,#"notifRemedyId",nil];
localnotif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localnotif];
Cancel as :
for (UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[aNotif.userInfo objectForKey: kRemindMeNotificationRemedyIDKey] isEqualToString:#"kRemindMeNotificationRemedyIDKey"]) {
if (remedyId == [[aNotif.userInfo objectForKey: kRemindMeNotificationRemedyIDKey] intValue]) {
[[UIApplication sharedApplication] cancelLocalNotification:aNotif];
break;
}
}
}
Hope it helps you.
I've created a old uilocalnotification, now, I want to update it, I searched on Google but there are no way to update the local notification. So, I decided to cancel it and create a new local notication:
- (void) cancelLocalNotificationByUserInfo: (NSDictionary *)dictInfo
{
UIApplication *application = [UIApplication sharedApplication];
NSArray *notifArr = [application scheduledLocalNotifications];
for (int i=0; i<notifArr.count; i++)
{
UILocalNotification* theNotif = (UILocalNotification *)[notifArr objectAtIndex:i];
if ([theNotif.userInfo isEqual:dictInfo])
{
[application cancelLocalNotification:theNotif];
}
}
}
- (void) addLocalNotification: (NSDate *) fireDate soundName: (NSString *) soundName
alertBody: (NSString *) alertBody infoDict: (NSDictionary *)infoDict
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = fireDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = alertBody;
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.hasAction = YES;
localNotif.applicationIconBadgeNumber = 1;
localNotif.soundName = soundName;
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
But, everytime, I execute the addLocalNotification method, the old local notification is fired immediately. Please help me!