We are having iPhone application which is communicating with apple watch application using network classes. We are using NWConnection and NWListener for peer to peer communication.
We have created UdpClient which is using bonjour service "camera.udp"
please check the code below UDPClient.swift
We have created UdpClient which is using bonjour service "camera.udp"
please check the code below UDPClient.swift
Code Block import Foundation import Network import WatchKit protocol UDPClientDelegate { func connectionDone() func dataSendSuccesfully() func socketConnectionStoped() func receivedReplyWithDict(dict : [String : Any]) } enum ConnectionState { case settingUP case started case dataBeingSent case disconnected } class UDPClient { var count : Int = 0 var udpDelegate: UDPClientDelegate? var connection : NWConnection? var queue : DispatchQueue = DispatchQueue.global(qos: .userInitiated) var serviceName : String? var connectedState : ConnectionState = .disconnected var dataArray : Array<Any> static let sharedInstance: UDPClient = { let instance = UDPClient() return instance }() init(){ dataArray = Array() } func setupConnection(name: String){ serviceName = name let parameters = NWParameters.udp // Create the connection connection = NWConnection(to: .service(name: name, type: "_camera._udp", domain: "local", interface: nil), using: parameters) // Set the state update handler connection?.stateUpdateHandler = { (newState) in switch (newState){ case .ready: print("Ready To Send") case .failed(let error): print("Connection State: \(error)") case .preparing: print("Preparing...") case .waiting(let error): print("Waiting: \(error)") default: print("def") break } } connectedState = .settingUP setupReceive() } func startConnection() { // Start the connection if(connectedState == .settingUP){ connection?.start(queue: queue) connectedState = .started } } func stopConnection(){ sendDisconnectACK() connection?.cancelCurrentEndpoint() connectedState = .disconnected connection = nil print("Stopped") } //MARK:- Receive Data func setupReceive() { if connection != nil{ connection?.receiveMessage { (content, context, isComplete, error) in if content != nil{ self.processReplyFromIOS(content: content!) } self.setupReceive() } }else{ return } } func processReplyFromIOS(content : Data){ var receivedData = [:] as [String : Any] do{ if let oppData = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(content){ receivedData = oppData as! [String : Any] } }catch let error{ print(error) } if receivedData["Connected"] != nil{ print("Got Connected") self.connectedState = .dataBeingSent }else{ } } //MARK:- Send Data // Send Connection data func sendConnectionRequest(){ WKInterfaceDevice.current().isBatteryMonitoringEnabled = true let dic = ["ConnetionRequest":"Request","batteryLevel":watchBatteryPercentage] as [String : Any] let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dic) connection?.send(content: dataExample, completion: .contentProcessed({ (error) in if let error = error{ print("Send error \(error)") } })) } var watchBatteryPercentage:Int { return Int(roundf(WKInterfaceDevice.current().batteryLevel * 100)) } func sendData(dic :[String : Any]){ let data: Data = NSKeyedArchiver.archivedData(withRootObject: dic) connection?.send(content: data, completion: .idempotent) } // Send Disconnection Ack func sendDisconnectACK(){ let disconnectionData = ["Disconnected" : true] as [String : Any] let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: disconnectionData) connection?.send(content: dataExample, completion: .contentProcessed({ (error) in if let error = error{ print("Send error \(error)") } })) } }