Bonjour Service Browser with Swift does not fetch serviceinfo

天涯浪子 提交于 2019-12-06 12:07:49

The error is that the services which are found in the ServiceBrowserDelegate function are not saved anywhere and therefore are discarded at the end of the function.

I found a working example here:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/61f0c753a080040e4a74b912e6c18dd97fe8bcaa/bk2ch24p853bonjour/ch37p1101bonjour/ViewController.swift

class ViewController: UIViewController, NetServiceBrowserDelegate, NetServiceDelegate {
var nsb : NetServiceBrowser!
var services = [NetService]()

@IBAction func doButton (_ sender: Any!) {
    print("listening for services...")
    self.services.removeAll()
    self.nsb = NetServiceBrowser()
    self.nsb.delegate = self
    self.nsb.searchForServices(ofType:"_daap._tcp", inDomain: "")
}

func updateInterface () {
    for service in self.services {
        if service.port == -1 {
            print("service \(service.name) of type \(service.type)" +
                " not yet resolved")
            service.delegate = self
            service.resolve(withTimeout:10)
        } else {
            print("service \(service.name) of type \(service.type)," +
                "port \(service.port), addresses \(service.addresses)")
        }
    }
}

func netServiceDidResolveAddress(_ sender: NetService) {
    self.updateInterface()
}

func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind aNetService: NetService, moreComing: Bool) {
    print("adding a service")
    self.services.append(aNetService)
    if !moreComing {
        self.updateInterface()
    }
}

func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didRemove aNetService: NetService, moreComing: Bool) {
    if let ix = self.services.index(of:aNetService) {
        self.services.remove(at:ix)
        print("removing a service")
        if !moreComing {
            self.updateInterface()
        }
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!