swiftmacoscocoabonjour

NetService failing to publish


I am attempting to do a simple test of publishing a bonjour service locally in Swift. I am doing this through a simple one view app that just creates a netService object and attempts to publish it. When I run the app it fails to publish, and the didNotPublish function is called by the delegate, generating the error

code -72004 ("An required argument was not provided when initializing the NSNetService instance").

I can't figure out what the missing argument might be, as I have specified each of domain, type, name and port.

class ViewController: NSViewController, NetServiceDelegate {

    var netService : NetService?

    override func viewDidLoad() {
        super.viewDidLoad()

        //initialize the NetService object
        self.netService = NetService(domain: "local.", type: "testService._tcp.", name: "netServiceTest", port: Int32(80))

        //assing NetService delegate to ViewController object
        self.netService!.delegate = self

        //publish it
        self.netService!.publish()
    }

    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }

    //netservice delegate functions
    func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {
        print("uh oh, could not publish netService. domain:\(netService!.domain) type:\(netService!.type) name:\(netService!.name) port:\(netService!.port)")
        print("error code:\(errorDict)")
    }

    func netServiceDidPublish(_ sender: NetService) {
        print("netService published.")
    }

    func netServiceDidStop(_ sender: NetService) {
        print("netService stopped.")
    }

    func netServiceWillPublish(_ sender: NetService) {
        print("Service will publish, apparently")
    }
}

Solution

  • Your type isn't properly set. You need to prefix type with an underscore.
    So it should look like this: "_testService._tcp."


    From NetService Documentation:

    type
    The network service type. type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.