3

我是 iOS 和 Cocoa 编程的新手,今天我想构建一个小型 iOS 应用程序来测试本地通知。通知工作正常,一切都像我预期的那样工作。我唯一的问题是,该方法application:didReceivedLocalNotification不想被调用:D

实现是这样工作的:UI 有一个滑块,用户可以在其中定义一个时间值,以秒为单位。在滑块上设置值后,LocalNotification 应在 xx 秒内触发。当我按下主页按钮时,通知会准时出现。但是当应用程序在前台时,通知不会出现。我已经实现了该方法并通过在方法的开头application:didReceivedLocalNotification放置一个来测试方法的调用,但是终端上没有输出。NSLog(@"YEEEAAH");

segue 似乎也有效。当我将线放在sliderTouched 的末尾时:segue 执行。

这是我的代码:

- (IBAction)sliderTouched:(UISlider *)sender {
    float seconds = [sender value];
    self.secondLabel.text = [NSString stringWithFormat:@"%d sec.", (int)seconds];

    UIApplication *theApplication = [UIApplication sharedApplication];
    UILocalNotification * theNotification = [[UILocalNotification alloc] init];
    [theApplication cancelAllLocalNotifications];
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:(int)seconds];
    theNotification.fireDate = fireDate;
    theNotification.timeZone = [NSTimeZone defaultTimeZone];
    theNotification.alertBody = @"Lalalala";
    theNotification.soundName = UILocalNotificationDefaultSoundName;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:fireDate];
    NSInteger hour = [components hour]%12;
    NSInteger minute = [components minute];
    NSInteger second = [components second];

    self.timeLabel.text = [NSString stringWithFormat:@"%02i:%02i:%02i", hour, minute, second];

    [theApplication scheduleLocalNotification:theNotification]; 
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    if (application.applicationState == UIApplicationStateActive) {
        [self performSegueWithIdentifier:@"modalView" sender:nil];
    }
}
4

2 回答 2

4

两个条件:-

1)如果您的应用程序处于 Not-Running 状态,则didFinishLaunchingWithOptions调用函数然后didReceiveLocalNotification调用

2)如果您的应用程序处于运行状态,即如果它处于前台或后台,则didReceiveLocalNotification调用

于 2013-03-19T17:22:23.167 回答
0

didReceiveRemoteNotification带有处理程序, didReceiveLocalNotification当我们在通知或应用程序处于前台时会调用它。

于 2015-08-11T10:20:01.913 回答