URLSessionWebSocketTask 在 iOS iMessage 扩展上失败;在常规应用程序中工作正常

问题描述 投票:0回答:0

我正在使用 URLSessionWebSocketTask 打开 Web 套接字 API 并进行交易。这在我的常规 iOS 应用程序中运行良好,但是,一旦我打开并尝试在 iOS 应用程序扩展中恢复 websocket 连接,我就会收到以下错误:

2023-03-01 18:04:42.030598-0800 VanGoMessagesExtension[537:19333] Connection not set before response is received, failing task
2023-03-01 18:04:42.031175-0800 VanGoMessagesExtension[537:19333] Task <46A8F9EB-5DD7-4872-B61D-A6D26C1284D8>.<3> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

我没有在文档中的任何地方看到应用程序扩展不支持 URLSessionWebSocketTask,但是完全相同的代码适用于 iOS 应用程序。

这里是相关代码的片段:

 let task = URLSession.shared.webSocketTask(with: url)
        self.task = task // This is the URLSessionWebSocketTask
        let jsonEncoder = JSONEncoder()

        let imageQueryBody = ImageQueryBody(user_id: userID, test: !useRealData, prompt: queryTerm, limit: limit)
        let imageQuery = ImageQuery(action: "getImageRequest", body: imageQueryBody)
        do {
            let jsonResultData = try jsonEncoder.encode(imageQuery)
            guard let jsonString = String(data: jsonResultData, encoding: .utf8) else {
                assertionFailure("Failed to convert request to JSON string")
                return
            }
            task.send(.string(jsonString)) { [weak self] error in
                guard let self = self else { return }
                if let error = error {
                    self.log(.error, "[Request id: \(self.requestID)] Failed to send request message to query API with error: \(error.localizedDescription)")
                    DispatchQueue.main.async {
                        self.task?.cancel(with: .internalServerError, reason: nil)
                        self.onComplete?(.failure(error))
                    }
                }
            }
            setupReceiveData() // This just sets up the receive handler 
            task.resume() 
        } catch {
            DispatchQueue.main.async {
                self.onComplete?(.failure(error))
            }
        }

我已经尝试重新调整我执行 task.send 和 task.resume 的顺序,但无济于事。我还在互联网上搜索了这个 API 在应用程序扩展上的问题,但没有找到任何细节。

ios swift nsurlconnection ios-app-extension
© www.soinside.com 2019 - 2024. All rights reserved.