iOS中Bonjour:NSNetServiceBrowser在子线程上使用

在iOS开发中,尝试在子线程启动NSNetServiceBrowser进行Bonjour服务搜索时遇到问题,因为NSNetServiceBrowser在当前运行循环中异步执行搜索。根据苹果文档,搜索过程在后台进行,结果通过委托对象返回。正确使用方法包括分配、初始化对象、设置委托,可以选择在特定运行循环上执行搜索。要开始搜索,首先获取可访问的域,然后选择一个域来查找服务。

    如果在子线程上创建一个NSNetServiceBrowser,并调用searchForServicesOfType开始搜索,发现不起作用。查看苹果的文档发现这么一段话:

A network service browser performs all searches asynchronously using the current run loop to execute the search in the background. Results from a search are returned through the associated delegate object, which your client application must provide. Searching proceeds in the background until the object receives a stop message.

To use an NSNetServiceBrowser object to search for services, allocate it, initialize it, and assign a delegate. (If you wish, you can also use the scheduleInRunLoop:forMode: and removeFromRunLoop:forMode: methods to execute searches on a run loop other than the current one.) Once your object is ready, you begin by gathering the list of accessible domains using either the searchForRegistrationDomains or searchForBrowsableDomains methods. From the list of returned domains, you can pick one and use the searchForServicesOfType:inDomain: method to search for services in that domain.

    也就是说NSNetServiceBrowser是使用run loop实现不断循环搜索的,类似于NSTimer,主线程中默认开启了runloop,而子线程中默认没有创建runloop,所以需要自己创建并开启一个RunLoop,然后把NSNetServiceBrowser使用scheduleInRunLoop:forMode: 添加到runloop里,这样Bonjour才能开始工作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值