UILocalNotification not firing

2019-04-11 00:10发布

问题:

I am very new to Cocoa Touch and Objective-C but I've gotten the pretty big points down and I am experimenting with the UIKit. I have a action linked to a button that changes a label and fires a UILocalNotification and this is the action method:

- (IBAction)changeLabel:(id)sender {
    self.LabelOne.text = @"WHAT UPPP!";
    self.NotifyOne.alertBody = @"Testtttttt";
    self.NotifyOne.alertAction = @"Got It.";
    self.NotifyOne.fireDate = nil;
}

There are no errors or warnings, but it's just not firing. Is there anything wrong with my action method?

UPDATE
Here is the App Delegate initialization that contains the UILocalNotification:

@interface LearnAppDelegate : NSObject <UIApplicationDelegate> {
    UIButton *_ModifyLabelButton;
    UILabel *_LabelOne;
    UILocalNotification *_NotifyOne;
}

@property (nonatomic, retain) IBOutlet UILocalNotification *NotifyOne;

回答1:

If you are wanting it show without a schedule (eg. when you press a button) then either use UIAlertView or add [application presentLocalNotificationNow:self.NotifyOne]; to your code.

UPDATE

Remove IBOutlet and make both declarations of UILocalNotification the same name. For example:

@interface LearnAppDelegate : NSObject <UIApplicationDelegate> {
    UIButton *_ModifyLabelButton;
    UILabel *_LabelOne;
    UILocalNotification *NotifyOne;
}

@property (nonatomic, retain) UILocalNotification *NotifyOne;

Remember to synthesize in your implementation (.m) file.

Also try this instead:

- (IBAction)changeLabel:(id)sender {
    self.LabelOne.text = @"WHAT UPPP!";
    NotifyOne = [[UILocalNotification alloc] init];
    if (NotifyOne) {
        NotifyOne.alertBody = @"Testtttttt";
        NotifyOne.alertAction = NSLocalizedString(@"Got It.", nil);
        NotifyOne.fireDate = nil;
        NotifyOne.soundName = nil;
        NotifyOne.applicationIconBadgeNumber = 0;
        [application presentLocalNotificationNow:NotifyOne];
        [NotifyOne release];
        NotifyOne = nil;
    }
}


回答2:

Are you ever scheduling the alarm? Here is code I use to fire alarms.

UILocalNotification *alarm = [[UILocalNotification alloc] init];
    if (alarm) {
        alarm.fireDate = [NSDate date];
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.soundName = @"alarmsound.caf";
        alarm.alertBody = @"Test message...";       
        [[UIApplication sharedApplication] scheduleLocalNotification:alarm];
        [alarm release];
    }


回答3:

A UILocalNotification isn't going to fire if you don't provide it with a fireDate and schedule it with your application instance. If you're trying to immediately present some sort of alert, perhaps you should try using UIAlertView.