您好我想找到所有人在同一个网络中使用我的应用程序,比如说它是一个wifi网络,然后我想让所有人在该特定网络中使用我的应用程序。
他们在我的数据库(mySQL)中存在的个人资料数据及其位置。我可以根据位置获取用户但我的问题是按网络查找它们。任何想法如何开始这样做?
答案 0 :(得分:1)
我不是说使用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或BlueTooth。
答案 1 :(得分:0)
进行服务发现的一种方法是让程序侦听端口,然后在想要被发现或在其他实体上进行轮询时在该端口上进行广播。 这些方面的东西。
socket = listen_and_stuff()
others = do_broadcast()
while(run)
if time to update
others = do_broadcast
if received request
reply with info about self
但是,广播取决于路由器设置,子网等,因此可能在所有情况下都不起作用。