Swift: netServiceBrowser didRemoveService MacOSX 10.13



我正在尝试运行NetServiceBrowser。一旦新的ZeroConf设备出现在网络上,它将立即检测到它。但是,它不会检测到设备何时从网络中删除。

netServiceBrowser(aNetServiceBrowser: NetServiceBrowser!, didRemoveService aNetService: NetService!, moreComing: Bool( 永远不会被调用。

我错过了什么吗?

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)
}        
}
}

为了完整起见,我发布了完整的答案,更正了didRemoveService函数的定义(感谢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)
}
}
}

相关内容

  • 没有找到相关文章