在iOS中对后台线程执行任务,即使应用程序进入后台也能继续执行:

编程入门 行业动态 更新时间:2024-10-19 14:30:35
本文介绍了在iOS中对后台线程执行任务,即使应用程序进入后台也能继续执行:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在后台线程上执行?即使用户按下主页按钮,执行也应在后台继续。

How to perform execution on a background thread? Execution should continue in the background even if the user presses the home button.

推荐答案

将这些属性添加到.h文件中

Add these properties to your .h file

@property (nonatomic, strong) NSTimer *updateTimer; @property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;

现在假设您对按钮有一个操作 - > btnStartClicked 那么您的方法将是喜欢:

Now suppose you have a action on button --> btnStartClicked then your method would be like :

-(IBAction)btnStartClicked:(UIButton *)sender { self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(calculateNextNumber) userInfo:nil repeats:YES]; self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ NSLog(@"Background handler called. Not running background tasks anymore."); [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid; }]; } -(void)calculateNextNumber{ @autoreleasepool { // this will be executed no matter app is in foreground or background } }

如果你需要停止使用这种方法,

and if you need to stop it use this method,

- (IBAction)btnStopClicked:(UIButton *)sender { [self.updateTimer invalidate]; self.updateTimer = nil; if (self.backgroundTask != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid; } i = 0; }

更多推荐

在iOS中对后台线程执行任务,即使应用程序进入后台也能继续执行:

本文发布于:2023-11-13 00:22:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   也能   线程   中对   应用程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!