I have used [NSURLSession sharedSession]
to get data from server.While getting the data if the app moves to background and after sometime if it comes to foreground I get "Connection was lost" error. So I implemented getting data in background and used beginBackgroundTaskWithExpirationHandler
. But the problem is after sometime the app restarts from the beginning since I ended background task which I don't want.Is there a way I fetch data when data is loading and app moves to background and on opening the app it should show the page it was prevoisly displaying before moving to background.
[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;
}