Reputation: 61
I'm pretty new in Swift 3.
I want to get the ip of my NetServices which I explored with bonjour to show them to the user, not to connect with the device. So far I can search for devices with bonjour and get them listed in a listView with this great access code:
https://github.com/ecnepsnai/BonjourSwift
This is my function to scan the bonjour services and put them into a local array of 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)
}
}
}
}
I'm using this method to get the ip address, from Swift 3 how to resolve 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)
}
And with this IBAction I just want to print the ip address, but my ip is empty and my bonjourServices[0].addresses
is empty also the addresses.adress NSData Objects
@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)
}
}
Here is my console output:
netServiceDidResolveAddress get called with <NSNetService 0x61800003d6a0> local. _printer._tcp. Brother HL-3152CDW series.
guard let data failed
()
Optional([])
Can you please help me resolve this problem?
Upvotes: 1
Views: 1278
Reputation: 61
I managed to solve my problem with this post: Bonjour Service Browser with Swift does not fetch serviceinfo
I did use Swift Development with Cocoa: Developing for the Mac and IOS App Stores published by O'Reilly for my code from page 299:
And then I had to make a call like this:
self.bonjourServices.removeAll()
self.browser = NetServiceBrowser()
self.browser.delegate = self
self.browser.searchForServices(ofType:"_raop._tcp", inDomain: "")
Now it's working fine and I got all data of my services.
Upvotes: 2