0

I'm using the URLSessionWebSocketTask to open up and transact with a web socket API. This is working fine in my regular iOS app, however, as soon as I open and try to resume the websocket connection in the iOS app extension, I am getting the following error:

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."

I'm not seeing anywhere in the documentation that the URLSessionWebSocketTask is not supported for app extensions, however the exact same code works fine for the iOS app.

Here is the snippet of the relevant code:

 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))
            }
        }

I have tried reshifting the order I do task.send, and task.resume, but to no avail. I've also searched the internet for issues with this API on app extensions but found no details.

0 Answers0