Post

Replies

Boosts

Views

Activity

Swift URLSession closes connection immediately, while Postman keeps it open (Sony TV PIN request)
Hello, I'm trying to implement a PIN request feature for a Sony TV in my iOS app. The goal is to keep the PIN entry window open on the TV until the user enters the PIN. However, I'm encountering an issue where the connection is closed immediately when using Swift's URLSession, while the same request works as expected in Postman. Here's my Swift code: let parameters = """ { "method": "actRegister", "params": [ { "clientid": "MyDevice:1", "nickname": "My Device", "level": "private" }, [ { "value": "yes", "function": "WOL" } ] ], "id": 1, "version": "1.0" } """ guard let postData = parameters.data(using: .utf8) else { completion(.failure(NSError(domain: "Invalid data", code: 0, userInfo: nil))) return } var request = URLRequest(url: URL(string: "http://\(ipAddress)/sony/accessControl")!,timeoutInterval: 30) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = postData let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { completion(.failure(error)) return } guard let data = data else { completion(.failure(NSError(domain: "No data received", code: 0, userInfo: nil))) return } if let responseString = String(data: data, encoding: .utf8) { print("Response: \(responseString)") } } task.resume() When I send this request using Postman, the PIN window on the TV stays open as expected. I receive a 401 response, which is normal for this type of request. In Postman, I can simulate the unwanted behavior by sending the request twice in quick succession, which closes the PIN window. However, when I run this code in the iPhone Simulator, the PIN window on the TV closes immediately after appearing. What I've tried: Increasing the timeoutInterval Using URLSession.shared.dataTask and URLSession(configuration:delegate:delegateQueue:) Implementing URLSessionDataDelegate methods Expected behavior: The PIN window should stay open on the TV until the user enters the PIN or a timeout occurs. Actual behavior: The PIN window appears briefly on the TV and then closes immediately. Questions: Why does the behavior differ between Postman and my Swift code? How can I modify my Swift code to keep the connection open and the PIN window displayed on the TV? Is there a way to prevent URLSession from automatically closing the connection after receiving the 401 response? Any insights or suggestions would be greatly appreciated. Thank you! Environment: iOS 15+ Swift 5 Xcode 13+
1
0
240
Sep ’24