NetWorkListener and NetworkConncetion listening and receiving error.

What is

"NetworkConstants.serviceName" "NetworkConstants.serviceType" in NetworkListener Class will you please suggest me. And

func didReceivedData(connection: NetworkConnection, with messageResponse: ConnectionMessage) what should be in "ConnectionMessage" and each of in "NetworkConnection" Class.

Reagards,

Narendra Sorathiya

None of the types you’ve mentioned here (NetWorkListener [sic], NetworkConncetion [sic], NetworkConstants, NetworkListener, NetworkConnection, ConnectionMessage) are Apple APIs. I have two theories here:

  • You’re using Apple APIs directly, but have misspelled the names here — In that case, please reply back with the correct details.

  • You’re using some wrapper around Apple APIs — If so, please dig through that wrapper to find the Apple APIs involved and post those details.

Also, what platform are you working on?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Class PeerBrowser

import Network

@available(iOS 13.0, *)

var sharedBrowser: PeerBrowser?

// Update the UI when you receive new browser results.

@available(iOS 13.0, *)

protocol PeerBrowserDelegate: AnyObject {

func refreshResults(results: Set<NWBrowser.Result>)

func displayBrowseError(_ error: NWError)

}

@available(iOS 13.0, *)

class PeerBrowser {

weak var delegate: PeerBrowserDelegate?

var browser: NWBrowser?



// Create a browsing object with a delegate.

init(delegate: PeerBrowserDelegate) {

	self.delegate = delegate

	startBrowsing()

}



// Start browsing for services.

func startBrowsing() {

	// Create parameters, and allow browsing over peer-to-peer link.

	let parameters = NWParameters()

	parameters.includePeerToPeer = true



	// Browse for a custom "_tictactoe._tcp" service type.

	let browser = NWBrowser(for: .bonjour(type: "_whitelion._udp", domain: nil), using: parameters)

	self.browser = browser

	browser.stateUpdateHandler = { newState in

		switch newState {

		case .failed(let error):

			// Restart the browser if it loses its connection

			if error == NWError.dns(DNSServiceErrorType(kDNSServiceErr_DefunctConnection)) {

				print("Browser failed with \(error), restarting")

				browser.cancel()

				self.startBrowsing()

			} else {

				print("Browser failed with \(error), stopping")

				self.delegate?.displayBrowseError(error)

				browser.cancel()

			}

		case .ready:

			// Post initial results.

			self.delegate?.refreshResults(results: browser.browseResults)

		case .cancelled:

			sharedBrowser = nil

			self.delegate?.refreshResults(results: Set())

		default:

			break

		}

	}



	// When the list of discovered endpoints changes, refresh the delegate.

	browser.browseResultsChangedHandler = { results, changes in

		self.delegate?.refreshResults(results: results)

	}



	// Start browsing and ask for updates on the main queue.

	browser.start(queue: .main)

}

}

Class PeerListener

import Network

@available(iOS 13.0, *)

var sharedListener: PeerListener?

@available(iOS 13.0, *)

class PeerListener {

weak var delegate: PeerConnectionDelegate?

var listener: NWListener?

var name: String



// Create a listener with a name to advertise, a passcode for authentication,

// and a delegate to handle inbound connections.

init(name: String, delegate: PeerConnectionDelegate) {

	self.delegate = delegate

	self.name = name

	startListening()

}



// Start listening and advertising.

func startListening() {

	do {

		// Create the listener object.

            let tcpOption = NWProtocolTCP.Options()

            tcpOption.enableKeepalive = true

            tcpOption.keepaliveIdle = 2

            

            let params = NWParameters(tls: nil, tcp: tcpOption)    /* Configure TLS here */

            params.includePeerToPeer = true

            

		let listener = try NWListener(using: params)

		self.listener = listener



		// Set the service to advertise.

		listener.service = NWListener.Service(name: self.name, type: "_whitelion._udp")



		listener.stateUpdateHandler = { newState in

			switch newState {

			case .ready:

				print("Listener ready on \(String(describing: listener.port))")

			case .failed(let error):

				// If the listener fails, re-start.

				if error == NWError.dns(DNSServiceErrorType(kDNSServiceErr_DefunctConnection)) {

					print("Listener failed with \(error), restarting")

					listener.cancel()

					self.startListening()

				} else {

					print("Listener failed with \(error), stopping")

					self.delegate?.displayAdvertiseError(error)

					listener.cancel()

				}

			case .cancelled:

				sharedListener = nil

			default:

				break

			}

		}



		listener.newConnectionHandler = { newConnection in

			if let delegate = self.delegate {

				if sharedConnection == nil {

					// Accept a new connection.

					sharedConnection = PeerConnection(connection: newConnection, delegate: delegate)

				} else {

					// If a game is already in progress, reject it.

					newConnection.cancel()

				}

			}

		}



		// Start listening, and request updates on the main queue.

		listener.start(queue: .main)

	} catch {

		print("Failed to create listener")

		abort()

	}

}



// If the user changes their name, update the advertised name.

func resetName(_ name: String) {

	self.name = name

	if let listener = listener {

		// Reset the service to advertise.

		listener.service = NWListener.Service(name: self.name, type: "_tictactoe._tcp")

	}

}

}

Class PeerConnection

import Foundation

import Network

@available(iOS 13.0, *)

var sharedConnection: PeerConnection?

@available(iOS 13.0, *)

protocol PeerConnectionDelegate: AnyObject {

func connectionReady()

func connectionFailed()

func receivedMessage(content: Data?, message: NWProtocolFramer.Message)

func displayAdvertiseError(_ error: NWError)

}

@available(iOS 13.0, *)

class PeerConnection {

weak var delegate: PeerConnectionDelegate?

var connection: NWConnection?

let initiatedConnection: Bool



// Create an outbound connection when the user initiates a game.

init(endpoint: NWEndpoint, interface: NWInterface?, delegate: PeerConnectionDelegate) {

	self.delegate = delegate

	self.initiatedConnection = true

        let connection = NWConnection(host: "255.255.255.255", port: 13001, using: .udp)

	self.connection = connection



	startConnection()

}



// Handle an inbound connection when the user receives a game request.

init(connection: NWConnection, delegate: PeerConnectionDelegate) {

	self.delegate = delegate

	self.connection = connection

	self.initiatedConnection = false



	startConnection()

}



// Handle the user exiting the game.

func cancel() {

	if let connection = self.connection {

		connection.cancel()

		self.connection = nil

	}

}



// Handle starting the peer-to-peer connection for both inbound and outbound connections.

func startConnection() {

	guard let connection = connection else {

		return

	}



	connection.stateUpdateHandler = { newState in

		switch newState {

		case .ready:

			print("\(connection) established")



			// When the connection is ready, start receiving messages.

			self.receiveNextMessage()



			// Notify your delegate that the connection is ready.

			if let delegate = self.delegate {

				delegate.connectionReady()

			}

		case .failed(let error):

			print("\(connection) failed with \(error)")



			// Cancel the connection upon a failure.

			connection.cancel()



			// Notify your delegate that the connection failed.

			if let delegate = self.delegate {

				delegate.connectionFailed()

			}

		default:

			break

		}

	}



	// Start the connection establishment.

	connection.start(queue: .main)

}



// Handle sending a "move" message.

func sendMove(_ move: String) {

	guard let connection = connection else {

		return

	}



	// Create a message object to hold the command type.

	let message = NWProtocolFramer.Message(gameMessageType: .move)

	let context = NWConnection.ContentContext(identifier: "Move",

											  metadata: [message])



	// Send the application content along with the message.

	connection.send(content: move.data(using: .unicode), contentContext: context, isComplete: true, completion: .idempotent)

}



// Receive a message, deliver it to your delegate, and continue receiving more messages.

func receiveNextMessage() {

	guard let connection = connection else {

		return

	}



	connection.receiveMessage { (content, context, isComplete, error) in

		// Extract your message type from the received context.

		if let gameMessage = context?.protocolMetadata(definition: GameProtocol.definition) as? NWProtocolFramer.Message {

			self.delegate?.receivedMessage(content: content, message: gameMessage)

		}

		if error == nil {

			// Continue to receive more messages until you receive and error.

			self.receiveNextMessage()

		}

	}

}

}

But although I got error like "No Route to Host"

Honestly, posting pages of code isn’t super helpful. I don’t have time to read through it all (especially in the context of DevForums).

Also, if you do post code, please format it as code. The standard way to do that is to enclose it in triple backquotes (or click the Code Block button). And if the code is too big for a single post, use a text attachment (the paperclip button).

Finally, I’d still like an answer to this:

what platform are you working on?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Actually I'm looking for multicast networking for home automation app for iOS 14.5 and later. I didn't find any proper solution. It is working on udpsocket. When I do run code on below 14.5 it is working properly but in iOS 14.5 or later it give me error like "No route to host".

Have you made the changes necessary to support local network privacy? If not, see the Local Network Privacy FAQ.

We didn’t enforce local network privacy for BSD Sockets code until iOS 14.5, so that would explain why you didn’t notice this in earlier iOS 14 releases.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The framework I used in our project is CocoaAsyncSocket.

Right, which is based on BSD Sockets. That explains why it worked without the multicast entitlement on iOS 14.x, x < 5, but now requires it.

And I have checked environment … and provisioning profile.

So, to be clear, you have:

  • Applied for and been granted the multicast networking entitlement?

  • Added that additional capability to your App ID?

  • Added the entitlement to your .entitlements file?

For detailed instructions on the last two points, see Using the Multicast Networking Additional Capability.

Totally no idea about this.

Is this problem restricted to the device? Or does it occur on the simulator as well?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The framework I used in our project is CocoaAsyncSocket.

Right, which is based on BSD Sockets. That explains why it worked without the multicast entitlement on iOS 14.x, x < 5, but now requires it.

And I have checked environment … and provisioning profile.

So, to be clear, you have:

  • Applied for and been granted the multicast networking entitlement?

  • Added that additional capability to your App ID?

  • Added the entitlement to your .entitlements file?

For detailed instructions on the last two points, see Using the Multicast Networking Additional Capability.

Totally no idea about this.

Is this problem restricted to the device? Or does it occur on the simulator as well?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

NetWorkListener and NetworkConncetion listening and receiving error.
 
 
Q