如何在后台模式下更改外部屏幕中的UIImageView



当我的ios应用程序处于后台模式时,我需要用UIImageView在外部屏幕上显示更改。

我使用此代码更改UIImageView

campaingTimer = [NSTimer scheduledTimerWithTimeInterval:timeFirstAd target:self selector:@selector(changeImage) userInfo:nil repeats:NO];

这在我的应用程序处于活动状态时有效,但在后台时,输入changeImage方法,但不更改图片。

NSTimer选择器不能保证在后台启动。除非你正在注册特定的权限,例如在后台播放音乐,并且你在后台实际做的任何事情都与你要求的权限直接相关,否则你应该假设在应用程序处于后台时你将无法执行代码,因为这会让你比试图找到解决方案更成功。

在这种情况下,似乎您想在经过这么长时间后更改图像。当应用程序处于前台时,您拥有的NSTimer(假设您的方法编写正确)将工作,但为了处理后台,我建议您收听appDidEnterBackground和appWillEnterForeground并发布通知(请参阅下面的示例代码)。

AppDelegate.m
================
- (void)applicationDidEnterBackground:(UIApplication *)application
{
  self.currentTime = [NSDate date];    
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNameForBecameActive object:nil userInfo:@{kUserInfoForBecameActive: self.currentTime}];
}
================
ViewController.m
================
- (void)viewDidLoad
{
   [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive:) name:kNotificationNameForBecameActive object:nil];
}
- (void)didBecomeActive:(NSNotification *)notification
{
   NSDate *sleepDate = notification.userInfo[kUserInfoForBecameActive];
   NSTimeInterval secondsPassed = [[NSDate date] timeIntervalSinceDate:sleepDate];
  if (secondsPassed >= timeFirstAd)
  {
      [self changeImage];
  }
   // reinitialize NSTimer
}
================

或者,您可以发布appDidEnterBackground和appWillEnterForeground的通知,并在那里节省时间,同时使NSTimer无效并重新启动它。

最新更新