我的UI使用UILabel的动画来指示特定的状态。我使用NSUserDefaults standardUserDefaults中的密钥打开和关闭该状态。在模拟“主页”按钮然后单击应用程序后应用程序变为活动状态时,动画将在模拟器中正确重新启动。但是,如果我模拟“锁定”按钮然后单击“主页”,它就无法正确重新启动。两个事件都显示在控制台中,方法 - (void)startFlashingButton在两种情况下都被调用。我无法弄清楚为什么它在一个案例中起作用而在另一个案件中起作用。我将不胜感激任何帮助。
编辑2/14/17:我读了其他与UINotification有关的董事会的几篇帖子。上班显然很困难。当通知进入应用程序委托时,我的动画会被触发。我想建立一种"请勿打扰"系统会在特定时间静音通知。我的理解是,这不能通过UINotification自动化,因为应用程序看不到通知,除非它是前面和中心或者它在后台并且用户点击其中一个操作按钮。如果应用程序处于后台并且用户忽略警报,则应用程序将不会被触发,因此无法知道是否已达到请勿打扰时间。此外,您无法使用NSTimer可靠地执行此操作,因为在应用程序暂停后,计时器将无法识别,这将在转到后台后不久即可识别。所以,简单地说,我有一个比没有运行的模拟更大的问题。但感谢你们所有人的回复。
这是startFlashingButton方法:
-(void) startFlashingButton
{
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
if([storage boolForKey:@"animation started"] == YES){
// Fade out the view right away
[UIView animateWithDuration:2.0
delay: 0.0
options: (UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction)
animations:^{
self.timerLabel.alpha = 0.0;
}
completion:^(BOOL finished){
// Wait one second and then fade in the view
[UIView animateWithDuration:1.0
delay: 2.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
self.timerLabel.alpha = 1.0;
}
completion:nil];
}];
}
[storage synchronize];
}
在-viewDidLoad中,我将应用程序设置为在激活时通知,如下所示:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startFlashingButton) name:UIApplicationDidBecomeActiveNotification object:nil];
在app delegate中,我会在应用程序进入后台时同步用户默认值,如下所示:
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
NSLog(@"application did enter background");
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
[storage synchronize];
答案 0 :(得分:0)
作为Apple关于background transition cycle州的文件
当用户按下主页按钮,按下睡眠/唤醒按钮,或者系统启动另一个应用程序时,前台应用程序将转换为非活动状态,然后转换为后台状态。这些转换导致调用app delegate的applicationWillResignActive:和applicationDidEnterBackground:methods。
因此,当您锁定然后按主页按钮时,应用程序可能会退出处于活动状态但不在后台。
尝试创建此辅助方法并在applicationWillResignActive:
和applicationDidEnterBackground:
-(void)saveUserDefaults {
NSLog(@"application did enter background");
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
[storage synchronize];
}
此外,请确保Application does not run in background
中的info.plist
设置为NO
,否则您的应用将转到suspended
。