title: How do I detect loss of connection from a web socket in my Swift App
body: <p>I am trying to detect loss of connection to my web socket in Swift. I have very little understanding of web sockets but I have tried googling for information but with little success. Here is my custom class providing a web socket service;</p>
  <pre><code>//
  //  Services.swift
  //  BetVictorTask
  //
  //  Created by Stephen Learmonth on 28/02/2022.
  //
  
  import UIKit
  
  protocol NetworkServicesDelegateProtocol: AnyObject {
      func sendStockInfo(stocksInfo: [String: StockInfo])
  }
  
  class NetworkServices: NSObject, URLSessionWebSocketDelegate {
      
      static let sharedInstance = NetworkServices()
      
      var webSocketTask: URLSessionWebSocketTask?
      
      var stocksInfo: [String: StockInfo] = [:]
      
      var socketResults: [String: [StockInfo]] = [:]
      
      weak var delegate: NetworkServicesDelegateProtocol?
      
      func fetchStockInfo(symbols: [String], delegate: CompanyPriceListVC) {
          
          self.delegate = delegate
          
          let urlSession = URLSession(configuration: .default)
          
          webSocketTask = urlSession.webSocketTask(with: FINNHUB_SOCKET_STOCK_INFO_URL!)
                  
          webSocketTask!.resume()
          
          for symbol in symbols {
              
              let string = FINNHUB_SOCKET_MESSAGE_STRING + symbol + &quot;\&quot;}&quot;
              
              let message = URLSessionWebSocketTask.Message.string(string)
              
              webSocketTask!.send(message) { error in
                  if let error = error {
                      print(&quot;Error sending message: \(error)&quot;)
                  }
                  
                  self.receiveMessage()
                  
              }
          }
      }
              
      private func receiveMessage() {
          
          self.webSocketTask!.receive { result in
                      
              switch result {
              case .failure(let error):
                  print(&quot;Error receiving message: \(error)&quot;)
                  
              case .success(.string(let jsonData)):
  
                  guard let stockData = jsonData.data(using: .utf8) else { return }
                  
                  self.socketResults = [:]
                  self.stocksInfo = [:]
                  
                  let decoder = JSONDecoder()
                  do {
                      let socketData = try decoder.decode(SocketData.self, from: stockData)
                      guard let stockInfoData = socketData.data else { return }
                      for stockInfo in stockInfoData {
                          let symbol = stockInfo.symbol
                          if self.socketResults[symbol] == nil {
                              self.socketResults[symbol] = [StockInfo]()
                          }
                          self.socketResults[symbol]?.append(stockInfo)
                      }
                      
                      for (symbol, stocks) in self.socketResults {
                          for item in stocks {
                              if self.stocksInfo[symbol] == nil {
                                  self.stocksInfo[symbol] = item
                              } else if item.timestamp &gt; self.stocksInfo[symbol]!.timestamp {
                                  self.stocksInfo[symbol] = item
                              }
                          }
                      }
                      
                      self.delegate?.sendStockInfo(stocksInfo: self.stocksInfo)
                      
                      self.receiveMessage()
                      
                  } catch {
                      print(&quot;Error converting JSON: \(error)&quot;)
                  }
                  
              default:
                  print(&quot;default&quot;)
              }
          }
      }
  
      func closeWebSocketConnection() {
          webSocketTask?.cancel(with: .goingAway, reason: nil)
      }
      
      func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
          print(&quot;Got here&quot;)
      }
      
      func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
          guard let error = error as? URLError else { return }
          
          print(&quot;got here&quot;)
          
          
      }
      
      func fetchCompanyInfo(symbol: String, completion: @escaping (CompanyInfo?, UIImage?)-&gt;()) {
          
          let urlString = FINNHUB_HTTP_COMPANY_INFO_URL_STRING + symbol + &quot;&amp;token=&quot; + FINNHUB_API_TOKEN
          
          guard let url = URL(string: urlString) else { return }
          
          let task = URLSession.shared.dataTask(with: url) { data, response, error in
              if let error = error {
                  print(&quot;Error fetching company info: \(error)&quot;)
              }
              guard let data = data else { return }
              let decoder = JSONDecoder()
              
              do {
                  let companyInfo = try decoder.decode(CompanyInfo.self, from: data)
                  
                  guard let logoURL = URL(string: companyInfo.logo) else { return }
                  
                  let task = URLSession.shared.dataTask(with: logoURL) { data, response, error in
                      if let error = error {
                          print(&quot;Error fetching logo image: \(error)&quot;)
                      }
                      guard let data = data else { return }
                      
                      guard let logoImage = UIImage(data: data) else { return }
                      
                      completion(companyInfo, logoImage)
                      
                  }
                  task.resume()
              } catch {
                  print(&quot;Error decoding JSON: \(error)&quot;)
                  completion(nil, nil)
              }
          }
          task.resume()
      }
  }
  
  
  </code></pre>
  <p>I have tried implementing;</p>
  <pre><code>    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
          print(&quot;Got here&quot;)
      }
  
  </code></pre>
  <p>and then run the app and turn off WiFi to simulate loss of connection but the urlSession method never gets called.</p>
  <p>How can I simulate loss of web socket connection while running my app and detect this disconnection. Also I need to think of a way to reconnect the web socket</p>