application:didReceiveLocalNotification:未调用

时间:2013-03-19 15:53:20

标签: ios cocoa-touch

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

实现方式如下:UI有一个滑块,用户可以在其中定义时间值,以秒为单位。在滑块上设置值后,应在xx秒内触发LocalNotification。当我按下主页按钮时,通知按时出现。但是当应用程序位于前台时,通知不会出现。我已经实现了方法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];
    }
}

2 个答案:

答案 0 :(得分:4)

两个条件: -

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

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

答案 1 :(得分:0)

当我们选中通知或应用程序位于前台时,将会调用带有处理程序和class SearchBase { private List<Entry> entries; // Or immediately sorted: TreeSet void addAll(String... terms) { fill list entries, and sort them } Collection<String> termsContaining(String sought) { binary search on entries rigth } }

didReceiveRemoteNotification