Post

Replies

Boosts

Views

Activity

HTTP requests timing out...
I am new to swift, so any advice would be appreciated. So the I have seen URL and URLSession return a timeout response, the android varient of my app does not show this issue. class HasInternet: ObservableObject { let monitor = NWPathMonitor() let queue = DispatchQueue(label: "Monitor") private var status: NWPath.Status = .requiresConnection @Published var isConnected = false init(){ monitor.pathUpdateHandler = { [weak self] path in if let url = URL(string: "https://google.com") { var request = URLRequest(url: url) request.httpMethod = "HEAD" request.timeoutInterval = 30 let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 30.0 sessionConfig.timeoutIntervalForResource = 60.0 URLSession(configuration: sessionConfig) .dataTask(with: request) { (_, response, error) -> Void in guard error == nil else { return } guard (response as? HTTPURLResponse)? .statusCode == 200 else { return } DispatchQueue.main.async { self?.isConnected = true } } .resume() } } monitor.start(queue: queue) } } Here is another place with the same behaviour. func post(dModel: DialogModel? = nil, url: String, type: responseTypes, body: [String: Any], headers: [headerType], async: Bool = true) { //async let semaphore = DispatchSemaphore(value: 0) let timeout: TimeInterval = 10 if let url = URL(string: url) { var request = URLRequest(url: url) request.httpMethod = "POST" request.timeoutInterval = 30 for header in headers { request.setValue(header.value, forHTTPHeaderField: header.key) } do { request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) } catch let error { self.processError(dModel: dModel, error: error.localizedDescription, type: .report) return } let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 30.0 sessionConfig.timeoutIntervalForResource = 60.0 URLSession(configuration: sessionConfig) .dataTask(with: request) { (data, response, error) -> Void in if let error = error { self.processError(dModel: dModel, error: error.localizedDescription, type: .report) if(async){ semaphore.signal() // Signal semaphore even in case of error } return } if let httpResponse = response as? HTTPURLResponse{ if let unWrappedData = data { if let httpResponseData = String(data: unWrappedData, encoding: .utf8) { self.parse(dModel: dModel, type: type, response: httpResponseData, statusCode: httpResponse.statusCode) } } } else { self.processError(error: "Invalid response") } if(async){ semaphore.signal() // Signal semaphore after processing the response } } .resume() if(async){ semaphore.wait(timeout: .now() + timeout) } } else { processError(error: "Invalid URL") } }
0
0
364
Jul ’24