Hey,
im trying to get the NWConnection on watchOS 6 working. The NWConnection is working completly fine in combination with the iPhone, but if I disconnect the iPhone (Airplane Mode, WiFi and Bluetooth Off) the connection is not working, but the apple watch is connected with the wifi.
Normally the Apple Watch (mine a Series 4) can connect to a server without an iPhone, too?
Here the minimal example code (Created Watch-App iOS-Project with XCode 11.5 - InterfaceBuilder). The only thing I changed is I added an Label to the Watch-Interface and the following InterfaceController.swift in WatchKit Extension:
(Just for Info. The Server will just return "OK MPD 0.19.0\n" at connect)
import WatchKit
import Foundation
import Network
class InterfaceController: WKInterfaceController {
@IBOutlet weak var label: WKInterfaceLabel!
private var connection : NWConnection?
private var dispatchQueue = DispatchQueue(label: "connection")
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
self.label.setText("Version")
let endpoint = NWEndpoint.hostPort(host: .name("192.168.178.10", nil), port: 6600)
let parameters = NWParameters.tcp
self.connection = NWConnection(to: endpoint, using: parameters)
self.connection?.stateUpdateHandler = .some({ (state) in
print("Received State=\(state)")
switch state {
case .ready:
self.label.setText("READY")
self.connection?.receive(minimumIncompleteLength: 1, maximumLength: 1024, completion: { (data, contentContext, isComplete, error) in
if let data = data, data.count > 0, let string = String(data: data, encoding: .utf8) {
let arr = string.components(separatedBy: "\n")
let VERSION_PREFIX = "OK MPD"
for item in arr {
if item.hasPrefix(VERSION_PREFIX) {
// Received Version
let version = item[item.index(item.startIndex, offsetBy: VERSION_PREFIX.count)...]
var text = String(version)
if let path = self.connection?.currentPath {
text += " - Uses Others=\(path.usesInterfaceType(.other)) Uses Wifi=\(path.usesInterfaceType(.wifi))"
}
self.label.setText(text)
break
}
}
}
})
break
case .waiting(let error):
self.label.setText("Waiting Error=\(error)")
break
case .failed(let error):
self.label.setText("Failed Error=\(error)")
default:
break
}
})
self.connection?.start(queue: self.dispatchQueue)
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
self.connection?.cancel()
super.didDeactivate()
}
}
It is because the Watch could not connect to a server without the iPhone or am I missing something?
Thanks and Regards
Adrian