preface

After iOS12, during AFNetworking requests, the app returns to the background, and the following error will occur, and the network request will be interrupted (only in the real computer, the simulator will not reappear).

HTTP load failed (error code: [1:53]) 2018-08-30 11:54:43.390749+0200 Background[2224:809685] Task < 7CD7b0DD-2CE2-400D-AC02-d66c0f4e4847 >.<7> finished with error - code: 39 2018-08-30 11:54:43.391271+0200 Background[2224:809125] Task < 7CD7b0DD-2CE2-400D-AC02-d66c0f4e4847 >.<7> Load Failed with error Error Domain=NSPOSIXErrorDomain Code=53"Software caused connection abort" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <7CD7B0DD-2CE2-400D-AC02-D66C0F4E4847>.<7>, _kCFStreamErrorDomainKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <7CD7B0DD-2CE2-400D-AC02-D66C0F4E4847>.<7>"
), _kCFStreamErrorCodeKey=53} [53]
failure The operation couldn’t be completed. Software caused connection abort
Copy the code

To deal with

This situation is caused by the replacement of apple iOS12 system background suspension logic, Apple promised to fix this problem in iOS13, but it should not be fixed

So we’ll handle this on our side, mainly in the AppDelegate: OC version:

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier taskId; @property (nonatomic, strong) NSTimer *timer; Application - (void) applicationDidEnterBackground: (UIApplication *) {/ / after the judge is to prevent the background to enter the time haven't finished into the front desk and led to the mandatory APP opens up a new taskkilloffif(self.taskId ! = UIBackgroundTaskInvalid){return; } self. TaskId = [application beginBackgroundTaskWithExpirationHandler: ^ (void) {/ / when the application background of time used up calls the end of this block / / at this point we need to background tasks,  [self endTask]; }]; / / simulation a long Task self. The timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 f target: the self selector:@selector(longTimeTask:) userInfo:nil repeats:YES]; }#pragma mark - Stops timer
-(void)endTask
{
   
   if(_timer ! = nil||_timer.isValid) { [_timer invalidate]; _timer = nil; // endBackgroundTask [[UIApplication sharedApplication] endBackgroundTask:_taskId]; _taskId = UIBackgroundTaskInvalid; // NSLog(@"Stop the timer"); }} - (void) longTimeTask:(NSTimer *)timer{// NSTimeInterval time =[UIApplication sharedApplication] backgroundTimeRemaining]; NSLog(@"Time left by system = %.02f Seconds", time);

}
Copy the code

The swift version:

var backgroundTask: UIBackgroundTaskIdentifier = .invalid

func applicationWillResignActive(_ application: UIApplication) {
        backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] inself? .endBackgroundTask() } } funcendBackgroundTask() {
        print("Background task ended.")
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = .invalid
    }
Copy the code