iOS12 锁屏后 BoringSSL

 查资料一天,埋坑半天,写文章两小时,读5分钟。 我在坑外,等着你会来 


现象

系统版本:iOS12

build configuration: Release

场景: 后台收到Push进入前台,触发网络请求。

Xcode 输出:

nw_socket_handle_socket_event [C58:1] Socket SO_ERROR [9: Bad file descriptor]

nw_socket_get_input_frames [C58:1] recvmsg(fd 33, 1024 bytes) [57: Socket is not connected]

[BoringSSL] nw_protocol_boringssl_error(1584) C49.1:2 Lower protocol stack error: 53

load failed with error Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort"


分析

BoringSSL,可能与ssl有关

nw_protocol_boringssl_error(1584)

nw_protocol_boringssl_error(1584)

结论为: 可能与App Transport Security Settings下的Allow Arbitrary Loads有关

Bad file descriptor, 应该是socket断开,使用了无效的句柄

iOS listen socket become bad file descriptor after screen lock

[[iOS 12 Beta 11] NSPOSIXErrorDomain Code=53: Software caused connection abort](https://github.com/AFNetworking/AFNetworking/issues/4279)

iOS 12, Xcode 10, URLSession data request is cancelled as soon as app is not in foreground with error code 53

结论为:

正常情况下app进入后台(锁屏或切app)后,断开了网络连接,app重新进入前台时,socket有可能超时,断开无效。

但 此次在iOS12下的bug在于: applicationWillEnterForeground及applicationDidBecomeActive之间新发起的请求,使用了失效的socket句柄。不知道是否为AFNetwork和Alamofire底层复用问题,还是NSURLSession的问题。


方案

经和@原鸣清沟通,发现我们的情况和他所遇到的情况并不相同,更接近于第2种判断,即socket句柄无效

1. 延时发起网络请求,延至applicationDidBecomeActive之后处理

2. 向系统要求后台任务权限。

3. 重新创建网络相关对象,抛弃原有网络对象。

个人为了快速fix bug采用了延时方案。在收到applicationDidBecomeActive消息通知后,延时0.0秒,处理网络请求及后台Push事件。但建议有心人,看是否可以通过AFNetworking获得链接状态等,采取处理。将bug fix在网络底层。


后续

经过测试发现

//iOS11.4.1

2018/11/30 16:06:46 AppDelegate -[AppDelegate applicationWillEnterForeground:] XX: apns push:

2018/11/30 16:06:46 APNSManager -[APNSManager userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:] XX: apns push

2018/11/30 16:06:46 AppDelegate -[AppDelegate applicationDidBecomeActive:] XX: apns push:

//iOS12.1

2018/11/30 16:13:25 AppDelegate -[AppDelegate applicationWillEnterForeground:] XX: apns push:

2018/11/30 16:13:25 APNSManager -[APNSManager userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:] XX: apns push 

2018/11/30 16:13:25 AppDelegate -[AppDelegate applicationDidBecomeActive:] XX: apns push:

2018/11/30 16:13:25 AppDelegate -[AppDelegate applicationWillResignActive:] XX: apns push:

2018/11/30 16:13:26 AppDelegate -[AppDelegate applicationDidBecomeActive:] XX: apns push:

iOS12.1在锁屏后,会多调用一次applicationWillResignActive。


Final

在applicationWillResignActive中使用beginBackgroundTaskWithName:expirationHandler:开启一个task比较nice

__block UIBackgroundTaskIdentifier bgTask  =

         [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"bg_task" expirationHandler:^{ 

      [[UIApplication sharedApplication] endBackgroundTask:bgTask];  

       bgTask = UIBackgroundTaskInvalid;   

  }];

你可能感兴趣的:(iOS12 锁屏后 BoringSSL)