chenzhongpu
chenzhongpu

Reputation: 6871

UILocalNotification : set iOS Alarm doesn't work

I want to set an alarm in iOS app.

I tried this according to How to set an Alarm in iOS?. Here is my main code :

 UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        [localNotif setFireDate:self.datePicker.date];
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        NSLog(@"fireDate %@", localNotif.fireDate);
        NSLog(@"datepicker %@", self.datePicker.date);

        [localNotif setRepeatInterval:0];
        localNotif.alertBody = @"some text";
        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.alertAction = @"...";

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

And I also found that : in iOS8,

In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications

So, I add the flowing in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType types = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

        UIUserNotificationSettings *mySettings =
        [UIUserNotificationSettings settingsForTypes:types categories:nil];

        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

    }

To my disappointed, when the fire date came, nothing happened. Did I miss other important code ?

Upvotes: 1

Views: 750

Answers (1)

Wain
Wain

Reputation: 119031

Local notifications are only displayed by iOS when the application is closed. If the application is open you need to implement the app delegate methods to receive local notification details and display the event yourself.

Upvotes: 3

Related Questions