进入后台网络请求无法回调

2021-03-10  本文已影响0人  tom__zhu

APP设置了backgroundMode,但是进入后台以后,在 -applicationDidEnterBackground:中发出的网络请求概率性无法进入成功或是失败回调。
从AFN issue里翻到一个解决方案,经过验证有效,但因为取法理论依据无法保证多机型多系统版本兼容。

-(void) performFetch {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *urlstr = @"http://wiki.XX.domain/rest/likes/1.0/content/80524087/likes";
        XXGetURLRequest *request = [[XXGetURLRequest alloc] initWithURL:urlstr];
        XXURLSessionDataTask *task = [XXHTTPSessionManager dataTaskWithGetRequest:request];
        [task startRequestWithSuccess:^(XXURLResponse *response) {
            id json = [response.data toJSON];
            NSLog(@"💫background success: %@", json);
        } failure:^(XXURLResponse *response) {
            NSLog(@"💫background failure: %@", response.error.description);
        }];
    });

}

Starting the fetch as background task with 0.1 sec delay seems to work to avoid the problem:

上一篇下一篇

猜你喜欢

热点阅读