我是 Swift 3 的新手。
我想获取我用 bonjour 探索的 NetServices 的 ip,以将它们展示给用户,而不是与设备连接。到目前为止,我可以使用 bonjour 搜索设备,并使用以下出色的访问代码将它们列在 listView 中:
https://github.com/ecnepsnai/BonjourSwift
这是我扫描 bonjour 服务并将它们放入本地 NetServices 数组的函数:
// scanning for services, delete old bonjourServices Array and fill it with new discovered services
var bonjourServices = [NetService]()
private func putServicesToArray(){
let browser: Bonjour = Bonjour()
_ = browser.findService(Bonjour.Services.Line_Printer_Daemon, domain: Bonjour.LocalDomain) { (services) in
self.bonjourServices.removeAll()
for service in browser.services {
if !(self.bonjourServices.contains(service)) {
self.bonjourServices.append(service)
}
}
}
}
我正在使用这种方法获取 ip 地址,从Swift 3 如何解析 NetService IP?
func netServiceDidResolveAddress(_ sender: NetService) {
print("netServiceDidResolveAddress get called with \(sender).")
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
guard let data = sender.addresses?.first else {
print("guard let data failed")
return
}
do {
try data.withUnsafeBytes { (pointer:UnsafePointer<sockaddr>) -> Void in
guard getnameinfo(pointer, socklen_t(data.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"])
}
}
} catch {
print(error)
return
}
let address = String(cString:hostname)
print("Adress:", address)
}
有了这个 IBAction,我只想打印 ip 地址,但我的 ip 是空的,我bonjourServices[0].addresses
的也是空的,addresses.adress NSData 对象
@IBAction func detectNetwork(_ sender: UIButton) {
print("putServiceToArray: ")
putServicesToArray()
for service in bonjourServices {
print(service)
}
bonjourTableView.reloadData()
if !(bonjourServices.isEmpty){
print(netServiceDidResolveAddress(bonjourServices[0]))
print(bonjourServices[0].addresses)
}
}
这是我的控制台输出:
netServiceDidResolveAddress get called with <NSNetService 0x61800003d6a0> local. _printer._tcp. Brother HL-3152CDW series.
guard let data failed
()
Optional([])
你能帮我解决这个问题吗?