通过UIBackgroundTaskIdentifier在后台挂起时依旧能执行代码

来源:互联网 发布:自学单片机知乎 编辑:程序博客网 时间:2024/05/20 05:46

通过UIBackgroundTaskIdentifier 实现在APP后台挂起时依旧能完成我们想要的功能。

这里通过计时器模拟后台操作。


@property (nonatomic,assign) UIBackgroundTaskIdentifier task;

在进入后台的方法中添加代码

- (void)applicationDidEnterBackground:(UIApplication *)application {          self.task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{                [[UIApplication sharedApplication] endBackgroundTask:self.task];        self.task = UIBackgroundTaskInvalid;            }];           __block int count = 0;    [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {                count ++;        NSLog(@"%d",count);            }];  }

控制台输出



原创粉丝点击