iosswiftbonjourmdnsnetwork-framework

Why are TXT Records set to nil when using NWBrowser for Network.framework?


I'm trying to get a list of Bonjour services running on my local network using Network.framework in Swift for my iOS application. In order to discover devices that are using the same protocol version as my application running, I need to be able to view the TXT records of the Bonjour services running on the network. However, when I try to print result.endpoint.txtRecord that always returns nil.

Below is an example of my code (that is simplified to focus on the key parts of this example):

let parameters = NWParameters.tcp
parameters.includePeerToPeer = true
parameters.allowLocalEndpointReuse = true

let browser = NWBrowser(for: .bonjour(type: "_tictactoe._tcp", domain: nil), using: parameters)

browser.browseResultsChangedHandler = { results, changes in
    for result in results {
        print("Browser result. txtRecords: \(result.endpoint.txtRecord)")
    }
}

Solution

  • It turns out that creating a NWBrowser using .bonjour will never give you the TXT records, and will always return nil. However, if you use .bonjourWithTXTRecord when creating your NWBrowser, you will get the TXT records as well.

    Additionally, for some reason you need to go through the result.metadata instead of the result.endpoint.txtRecord to get the actual records.

    Below is an example of this in action.

    let browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_tictactoe._tcp", domain: nil), using: parameters)
    
    browser.browseResultsChangedHandler = { results, changes in
        for result in results {
            if case NWBrowser.Result.Metadata.bonjour(let txtRecord) = result.metadata {
                print("Browser result with txt records: \(txtRecord.dictionary)")
            }
        }
    }