Swift: netServiceBrowser didRemoveService MacOSX 10.13

334 views Asked by At

I am trying to run a NetServiceBrowser. It will detect a new ZeroConf device as soon as it appears on the network. It doesn't however detect when the device is removed from the network.

netServiceBrowser(aNetServiceBrowser: NetServiceBrowser!, didRemoveService aNetService: NetService!, moreComing: Bool) is never called.

Am I missing something?

class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelegate
{
    var browser: NetServiceBrowser
    var services = [NetService]()
    static let instance = BonjourDiscovery()

    override init()
    {
        browser = NetServiceBrowser()
        services = []
    }

    func startDiscovery()
    {
        browser.delegate = self
        browser.searchForServices(ofType: "_smb._tcp.", inDomain: "")
    }

    func stopDiscovery()
    {
        browser.stop()
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool)
    {
        print ("Found:" + service.name)
        self.services.append(service)
    }

    func netServiceBrowser(aNetServiceBrowser: NetServiceBrowser!, didRemoveService aNetService: NetService!, moreComing: Bool)
    {
        print ("Removed:" + aNetService.name)

        if let index = services.index(of: aNetService)
        {
            services.remove(at: index)
        }        
    }
}
1

There are 1 answers

0
iphaaw On BEST ANSWER

For completeness I have posted the full answer, correcting the didRemoveService function definition (Thanks to Martin R):

class BonjourDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelegate
{
    var browser: NetServiceBrowser
    var services = [NetService]()
    static let instance = BonjourDiscovery()

    override init()
    {
        browser = NetServiceBrowser()
        services = []
    }

    func startDiscovery()
    {
        browser.delegate = self
        browser.searchForServices(ofType: "_smb._tcp.", inDomain: "")
    }

    func stopDiscovery()
    {
        browser.stop()
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool)
    {
        print ("Found:" + service.name)
        self.services.append(service)
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool)
    {
        print ("Removed:" + service.name)

        if let index = services.index(of: service)
        {
            services.remove(at: index)
        }
    }
}