【发布时间】:2021-03-09 04:54:03
【问题描述】:
我使用[NSURLSession sharedSession] 从服务器获取数据。如果应用程序移至后台获取数据,一段时间后如果移至前台,我会收到“连接丢失”错误。所以我实现了在后台获取数据并使用beginBackgroundTaskWithExpirationHandler。但问题是应用程序从头开始重新启动,因为我结束了我不想要的后台任务。有没有办法在数据加载和应用程序移动到后台并打开应用程序时获取数据,它应该显示页面它在移动到背景之前预先显示。
[self beginBackgroundUpdateTask];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable responseData,
NSURLResponse * _Nullable urlResponse,
NSError * _Nullable error) {
if (error) {
NSLog(@"dataTaskWithRequest error: %@", error);
}
else{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
if([httpResponse statusCode ]>=200 && [httpResponse statusCode]<300)
{
//Do UI related things
}
else
{
//Display error here
}
[self endBackgroundUpdateTask];
}]resume];
- (void) beginBackgroundUpdateTask
{
backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: backgroundUpdateTask];
backgroundUpdateTask = UIBackgroundTaskInvalid;
}
【问题讨论】:
-
不确定我是否得到了最后一个问题 - 是关于后台任务还是应用程序状态恢复的问题?查看Preserving Your App's UI Across Launches 文档
-
@ATV 它是关于在后台获取应用程序数据。当应用程序移动到后台获取数据时,由于异步请求不在后台获取数据,我得到连接丢失错误。为此,我使用了 beginBackgroundUpdateTask。但是使用它会杀死我的应用程序并且不会恢复在移动到背景之前显示的视图控制器的状态。因此,由于 beginBackgroundUpdateTask,应用程序总是从头开始。如何显示之前显示的视图控制器
标签: ios iphone xcode ipad nsurlsession