我正在尝试运行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)
}
}
}
答案 0 :(得分:0)
为完整起见,我已发布完整答案,更正了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)
}
}
}