我并不是说使用 Bonjour (Zeroconf) 是实现您想要的最佳方式 - 但您当然可以使用它来实现您的目标。
Bonjour 有两种使用方式:
- 发布服务
- 检测(浏览)可用服务
对于你的任务,你必须同时做这两个。
一个基本的描述可以在这里找到:Bonjour Overview and its application in iOS
如果您决定使用 Bonjour,那么您会在 Bonjour for Developers 上找到大量文档
基本上,你需要发布一个服务:Bonjour Programming > Section 18.2. Publishing a Service
发布类(通常是appDelegate)也应该是NSNetService 委托。
NSNetService *netService; //an ivar or a property
//creating and publishing a service
netService = [[NSNetService alloc] initWithDomain:@""
type:@"_yourservicename._tcp."
name:@""
port:9876];
//if your app actually acts as a server port: should be it's port,
//otherwise it could be any free port
netService.delegate = self;
[netService publish];
您还应该处理委托方法(和一些appDelegate 方法):
-(void)netService:(NSNetService *)aNetService
didNotPublish:(NSDictionary *)dict
{
NSLog(@"Service did not publish: %@", dict);
}
- (void)applicationWillTerminate:(UIApplication *)application {
//---stop the service when the application is terminated---
[netService stop];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
//---stop the service when the application is paused---
[netService stop];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[netService publish];
}
并浏览现有服务:Bonjour! (cocoanetics)
(您只需要页面底部)
serviceBrowser = [[NSNetServiceBrowser alloc] init];
serviceBrowser.delegate = self;
[serviceBrowser searchForServicesOfType:@"_yourservicename._tcp." inDomain:@""];
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser
didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
[self willChangeValueForKey:@"foundServices"];
[_foundServices addObject:aNetService];
[self didChangeValueForKey:@"foundServices"];
NSLog(@"found: %@", aNetService);
}
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser
didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
[self willChangeValueForKey:@"foundServices"];
[_foundServices removeObject:aNetService];
[self didChangeValueForKey:@"foundServices"];
NSLog(@"removed: %@", aNetService);
}
PS:Bonjour 可能一开始可能会很棘手,但它肯定是一个有用的知识。
取决于您想要的用户体验。 Bonjour 的一个很好的替代品肯定是
成为GameKit (GKPeerPickerController) 用户实际上可以
选择要连接的设备(他想连接的对等设备)。
这应该可以在 Wi-Fi 或蓝牙中工作。