在Swift应用程序上使用NSNetService和NSNetServiceBrowser

时间:2014-07-07 20:09:47

标签: swift bonjour nsnetservice nsnetservicebrowser

我想创建一个能够发现并连接到本地网络上的同行的应用程序,因此我决定使用bonjour框架在swift中实现它。

但是,我无法使用Swift使Bonjour工作,我无法弄清楚原因。以下是我用来测试此服务的代码:

import Foundation

let BM_DOMAIN = "local"
let BM_TYPE = "_helloworld._tcp."
let BM_NAME = "hello"
let BM_PORT : CInt = 6543

/// Netservice
let nsns = NSNetService(domain: BM_DOMAIN, 
        type: BM_TYPE, name: BM_NAME, port: BM_PORT)
let nsnsdel = BMNSDelegate() //see bellow
nsns.delegate = nsnsdel
nsns.publish()

/// Net service browser.
let nsb = NSNetServiceBrowser()
let nsbdel = BMBrowserDelegate() //see bellow
nsb.delegate = nsbdel
nsb.searchForServicesOfType(BM_TYPE, inDomain: BM_DOMAIN)

println("press enter")
// this prevents the app from quitting instantly.
NSFileHandle.fileHandleWithStandardInput().availableData 

代表是胶水代码,只是打印每次调用控制台。

class BMNSDelegate : NSObject, NSNetServiceDelegate {
    func netServiceWillPublish(sender: NSNetService!) {
        println("netServiceWillPublish:sender");
    }
    // .....and so on for the 8 other methods.....
}

class BMBrowserDelegate : NSObject, NSNetServiceBrowserDelegate {
    func netServiceBrowserWillSearch(aNetServiceBrowser: NSNetServiceBrowser!){
        println("netServiceBrowserWillSearch")
    }
    // .....and so on for the 6 other methods.....
}

以下是此示例代码的输出:

netServiceWillPublish:sender
netServiceBrowserWillSearch
press enter

如果我使用Bonjour browser,我可以看到该服务已正确发布。但是,除了**WillPublish之外,两个代理中的回调都没有被调用: - (

经过深入调试(并在stackoverflow上阅读)后,我无法确定它为什么不起作用。有任何想法吗 ?

(我使用的是Mac OS X 10.9.3,xcode 6.0 beta build 6A215l)

2 个答案:

答案 0 :(得分:2)

NSNetServiceBrowser需要runloop才能执行。而不是从标准输入读取,请致电NSRunLoop.currentRunLoop().run()

答案 1 :(得分:2)

如果没有完整的代码,可能很难确定您的问题是什么。我怀疑你声明你的变量/常量是函数的局部。当它们超出范围时,对服务的引用超出了范围。这就是为什么你尝试了一个阻止调用来请求STDIN输入的原因(以防止事情陷入困境)。根据Apple文档,netService和netServiceBrowser都默认与默认运行循环相关联,因此您也不需要明确地执行此操作。显式关联运行循环会导致程序卡住,这不是您想要的。此代码创建以下输出

netServiceWillPublish:<NSNetService 0x14522e00> local _helloworld._tcp. hello
netServiceBrowserWillSearch
netServiceDidPublish:<NSNetService 0x14522e00> local. _helloworld._tcp. hello
netServiceDidFindService

并且没有被阻止或在运行循环中阻止程序正常进行。在AppDelegate.swift中

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

var nsns:NSNetService?
var nsnsdel:BMNSDelegate?
var nsb:NSNetServiceBrowser?
var nsbdel:BMBrowserDelegate?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.


    let BM_DOMAIN = "local"
    let BM_TYPE = "_helloworld._tcp."
    let BM_NAME = "hello"
    let BM_PORT : CInt = 6543

    /// Netservice
    nsns = NSNetService(domain: BM_DOMAIN,
        type: BM_TYPE, name: BM_NAME, port: BM_PORT)
    nsnsdel = BMNSDelegate() //see bellow
    nsns?.delegate = nsnsdel
    nsns?.publish()

    /// Net service browser.
    nsb = NSNetServiceBrowser()
    nsbdel = BMBrowserDelegate() //see bellow
    nsb?.delegate = nsbdel
    nsb?.searchForServicesOfType(BM_TYPE, inDomain: BM_DOMAIN)

    //println("press enter")
    // this prevents the app from quitting instantly.
    // NSRunLoop.currentRunLoop().run()
    // NSFileHandle.fileHandleWithStandardInput().availableData

    return true
}

和其他地方的委托回调......

class BMNSDelegate : NSObject, NSNetServiceDelegate {
func netServiceWillPublish(sender: NSNetService!) {
    println("netServiceWillPublish:\(sender)");
}

func netService(sender: NSNetService, didNotPublish errorDict: [NSObject : AnyObject]) {
    println("didNotPublish:\(sender)");
}

func netServiceDidPublish(sender: NSNetService) {
    println("netServiceDidPublish:\(sender)");
}

func netServiceWillResolve(sender: NSNetService) {
    println("netServiceWillResolve:\(sender)");
}

func netService(sender: NSNetService, didNotResolve errorDict: [NSObject : AnyObject]) {
    println("netServiceDidNotResolve:\(sender)");
}

func netServiceDidResolveAddress(sender: NSNetService) {
    println("netServiceDidResolve:\(sender)");
}

func netService(sender: NSNetService, didUpdateTXTRecordData data: NSData) {
    println("netServiceDidUpdateTXTRecordData:\(sender)");
}

func netServiceDidStop(sender: NSNetService) {
    println("netServiceDidStopService:\(sender)");
}

func netService(sender: NSNetService,
    didAcceptConnectionWithInputStream inputStream: NSInputStream,
    outputStream stream: NSOutputStream) {
        println("netServiceDidAcceptConnection:\(sender)");
}
}

class BMBrowserDelegate : NSObject, NSNetServiceBrowserDelegate {

func netServiceBrowser(netServiceBrowser: NSNetServiceBrowser,
                            didFindDomain domainName: String,
                            moreComing moreDomainsComing: Bool) {
    println("netServiceDidFindDomain")
}

func netServiceBrowser(netServiceBrowser: NSNetServiceBrowser,
                            didRemoveDomain domainName: String,
                            moreComing moreDomainsComing: Bool) {
    println("netServiceDidRemoveDomain")
}

func netServiceBrowser(netServiceBrowser: NSNetServiceBrowser,
    didFindService netService: NSNetService,
    moreComing moreServicesComing: Bool) {
        println("netServiceDidFindService")
}

func netServiceBrowser(netServiceBrowser: NSNetServiceBrowser,
    didRemoveService netService: NSNetService,
    moreComing moreServicesComing: Bool) {
        println("netServiceDidRemoveService")
}

func netServiceBrowserWillSearch(aNetServiceBrowser: NSNetServiceBrowser!){
    println("netServiceBrowserWillSearch")
}

func netServiceBrowser(netServiceBrowser: NSNetServiceBrowser,
    didNotSearch errorInfo: [NSObject : AnyObject]) {
        println("netServiceDidNotSearch")
}

func netServiceBrowserDidStopSearch(netServiceBrowser: NSNetServiceBrowser) {
    println("netServiceDidStopSearch")
}

}