gpt4 book ai didi

ios - 运行 NSTimer 但不更新 UILabel 的 UIBackgroundTaskIdentifier - iOS

转载 作者:行者123 更新时间:2023-11-29 11:51:41 28 4
gpt4 key购买 nike

在我的应用程序中,我有 NSTimer 每秒更新一次 UILabel。我在 NSTimer 之前添加了 UIBackgroundTaskIdentifier 以让它在后台运行。

__block UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];


timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];

[[NSRunLoop mainRunLoop] addTimer:updateTimer forMode:NSRunLoopCommonModes];

...

-(void)updateTime
{
secondsLeft -= 1;
//NSLog(@"Update time : %d ......",secondsLeft);
dispatch_async(dispatch_get_main_queue(), ^{
_timeLbl.text = [NSString stringWithFormat:@"%d",secondsLeft];
});
}

问题是当我们按下主页按钮时应用程序进入后台,计时器正在运行但 uilabel 没有更新。例如。比如,_timeLbl 显示“45”。现在,如果我按下主页按钮,应用程序将进入后台。 10 秒后。我单击应用程序图标将应用程序置于前台,然后我看到“45”一会儿(秒的分数)然后它显示 35,而不是直接显示 35。这意味着标签没有得到使用 NSTimer 更新。有什么解决方法可以解决这个问题吗?

谢谢!

最佳答案

应用委托(delegate)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{

[[UIApplication sharedApplication]setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

}



- (void)applicationWillResignActive:(UIApplication *)application {

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

}];
}

您的 Controller .M

- (void)viewDidLoad {

[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];

}

-(void) timerTick:(NSTimer *)timer1 {

int seconds = pauseTaskTime % 60;
int minutes = (pauseTaskTime - seconds) / 60;

lblTimer.text = [NSString stringWithFormat:@"%d:%.2d", minutes, seconds]
}

完成代码后,请执行以下步骤:

1. Go to your project name.

2. Click Capabilities

3. On your Background Modes.

谢谢

关于ios - 运行 NSTimer 但不更新 UILabel 的 UIBackgroundTaskIdentifier - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40841720/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com