前几天发现App中有一种情况,就是当前接口正在请求,还没返回数据,这时退到桌面,再切回App的时候,这个请求会中断。
解决方法如下:
@interface AppDelegate ()
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier taskId;
@property (nonatomic, strong) NSTimer *timer;
@end
- (void)applicationDidEnterBackground:(UIApplication *)application {
self.taskId = [application beginBackgroundTaskWithExpirationHandler:^(void) {
//当申请的后台时间用完的时候调用这个block
[self endTask];
}];
self.timer =[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(longTimeTask:)
userInfo:nil
repeats:YES];
}
- (void) longTimeTask:(NSTimer *)timer{
NSTimeInterval time =[[UIApplication sharedApplication] backgroundTimeRemaining];
DebugNsLog(@"剩余时间 = %.02f Seconds", time);
}
#pragma mark - 停止timer
-(void)endTask
{
if (_timer != nil||_timer.isValid) {
[_timer invalidate];
_timer = nil;
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
self.taskId = UIBackgroundTaskInvalid;
DebugNsLog(@"停止timer");
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[self endTask];
}