title: Swift: In NWConnection class when does receiveMessage(completion:) gets called
body: <p>I wanna have UDP connection with a wifi module as a server and an iOS as a client and send/receive data (obviously).First i wanted to use Sockets but then i realized Apple has introduced <code>Network</code> Framework; So i used <code>NWConnection</code> which is a class from <code>Network</code> Framework for my purpose and i was successful at sending the data to the device but unable to receive the response (which i am sure exists as i monitor devices I/O packets via serial port monitor).Here is a test version of  the code where i use <code>netcat</code> as server to test the connection:<br> </p>
  
  <ul>
  <li>ViewController Class<br></li>
  </ul>
  
  <pre><code>import UIKit
  import Network
  
  class ViewController: UIViewController
  {
      var network: UDPNetwork!
  
      override func viewDidLoad()
      {
          super.viewDidLoad()
  
      }
  
      @IBAction func button(_ sender: Any)
      {
          self.network = UDPNetwork(host: "192.168.200.4", port:"4210")!
          self.network.connect()
      }
  }
  </code></pre>
  
  <ul>
  <li>UDPNetwork Class<br></li>
  </ul>
  
  <pre><code>import Foundation
  import Network
  
  class UDPNetwork {
  
      var hostUDP: NWEndpoint.Host
      var portUDP: NWEndpoint.Port
  
      private var connection: NWConnection?
  
      private var queue = DispatchQueue(label: "NetworkQuue", qos: .utility)
  
      init?(host: String, port: String) {
  
          guard !host.isEmpty, let portUDP = NWEndpoint.Port(port) else {
              return nil
          }
  
          self.hostUDP = NWEndpoint.Host(host)
          self.portUDP = portUDP
      }
  
  
      func connect()
      {
          connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)
          connection?.stateUpdateHandler =
              {
                  (newState) in switch (newState)
                  {
                  case .ready:
                      //The connection is established and ready to send and recieve data.
                      print("ready")
                      self.sendPaket("Hello")
                      self.receive()
                  case .setup:
                      //The connection has been initialized but not started
                      print("setup")
                  case .cancelled:
                      //The connection has been cancelled
                      print("cancelled")
                  case .preparing:
                      //The connection in the process of being established
                      print("Preparing")
                  default:
                      //The connection has disconnected or encountered an error
                      print("waiting or failed")
                  }
          }
          connection?.start(queue: self.queue)
      }
  
      func sendPaket(_ packet:String)
      {
          let packetData = packet.data(using: .utf8)
          self.connection?.send(content: packetData, completion: NWConnection.SendCompletion.contentProcessed(({ (error) in
              if let err = error {
                  print("Sending error \(err)")
              } else {
                  print("Sent successfully")
              }
          })))
  
      }
  
      func receive()
      {
          self.connection?.receiveMessage(completion:
              {
                  (data, context, isComplete, error) in
                  print("Got it")
                  if let err = error {
                      print("Recieve error: \(err)")
                  }
  
                  if let rcvData = data,
                      let str = String(data:rcvData, encoding: .utf8) {
                      print("Received: \(str)")
                  }
  
                  self.receive()
  
          })
      }
  
  }
  </code></pre>
  
  <p>Apple Documentation says:</p>
  
  <blockquote>
    <p><code>receiveMessage(completion:)</code><br>
    Schedules a single receive completion handler for a complete message</p>
    
    <blockquote>
      <p><strong>completion</strong> :<br>
      A receive completion is invoked exactly once for a call to receive.</p>
    </blockquote>
  </blockquote>
  
  <ul>
  <li>My Question is:
  
  <ol>
  <li>How can we <strong><em>call to receive</em></strong> ?</li>
  <li>Assuming the <code>receiveMessage(completion:)</code> method <strong>is</strong> the <strong><em>Call to receive</em></strong> and also after receiving complete message calls the completion itself, What could be the problem if it doesn't get invoked?</li>
  </ol></li>
  </ul>
  
  <p>Related code and more detail about my use case can be found here:<br>
  <a href="https://stackoverflow.com/questions/58401093/swift-receiving-udp-packets-from-server-on-serial-port-monitor-but-not-in-ios-a?noredirect=1#comment103158827_58401093">Swift: Receiving UDP packets from server on serial port monitor but not in ios app</a></p>
  
  <p>With these assumptions :</p>
  
  <blockquote>
    <ul>
    <li>We call to receive on the same connection that we send data to</li>
    <li>UDP is used method for connection</li>
    <li>Server is tested for swapping ports correctly, meaning it responds  on the same IP,Port that data is sent to<br></li>
    </ul>
  </blockquote>
  
  <ul>
  <li>My Setup:<br>
  13" MacBookPro Early 2015 with MacOS Catalina 10.15 <br>
  Xcode Version 11.0 (11A420a) <br>
  Swift 5.1 <br>
  target iOS 12+ <br></li>
  </ul>
  
  <p>And this is the result from Wire Shark:
  <a href="https://i.stack.imgur.com/NqNAx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NqNAx.png" alt="enter image description here"></a></p>