【发布时间】:2021-06-27 15:08:32
【问题描述】:
所以我使用的是 iOS 13 的 URLSessionWebSocket 功能。
我有一个屏幕应该每隔 X 秒发送一个 ping 到另一个套接字。 在用户将应用移至后台之前,一切正常。
由于我不需要在后台执行任何请求,我正在尝试暂停所有 URLSessionWebSocketTasks,直到应用程序回到前台。
在我的代码中,我有几个任务存储在 socketConnections 字典中。 我还有一个名为“inForeground”的 BehaviorSubject 表示状态。 我正在收听 UIScene 的后台/前台通知并这样做:
@objc func appDidMoveToBackground(_ notification: Notification) {
inForeground.onNext(false)
for (taskId, task) in socketConnections {
task.suspend()
}
}
@objc func appDidBecomeActive(_ notification: Notification) {
inForeground.onNext(true)
for (id, task) in socketConnections {
task.resume()
setReceiveHandler(id)
}
}
private func setReceiveHandler(_ taskId: String) {
guard let foregroundState = try? self.inForeground.value(), foregroundState else {
print("not in foreground")
return
}
socketConnections[taskId]?.receive { [unowned self] result in
do {
let message = try result.get()
print("\(message)")
self.setReceiveHandler(taskId)
} catch let error {
print(error.localizedDescription)
}
}
}
当我移到后台然后移到前台时,我仍然得到错误:
nw_read_request_report [C16] 接收失败,出现错误“软件导致连接中止”
和
[websocket] 读取完成但出现错误软件导致连接中止
然后:
连接 16:收到失败通知
有什么想法会出错吗?
【问题讨论】: