Create a gist now

Instantly share code, notes, and snippets.

Easy Bonjour Browsing
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// other code here...
[[RBServerLocator sharedLocator] locateServerMatchingType:@"_myapp._tcp"
completion:^(NSNetService *service) {
NSLog(@"found server: %@", [service RBResolvedURL]);
}];
// other code here...
}
//
// RBServerLocator.h
//
// Created by Justin Voss on 12/9/11.
//
#import <Foundation/Foundation.h>
@interface RBServerLocator : NSObject <NSNetServiceBrowserDelegate, NSNetServiceDelegate>
{
void (^__completion_block)(NSNetService *);
NSMutableArray *__foundServices;
}
@property (strong, nonatomic) NSNetServiceBrowser *serviceBrowser;
+ (RBServerLocator *)sharedLocator;
- (void)locateServerMatchingType:(NSString *)type completion:(void (^)(NSNetService *))completionBlock;
@end
@interface NSNetService (RBResolvedURL)
- (NSURL *)RBResolvedURL;
@end
//
// RBServerLocator.m
//
// Created by Justin Voss on 12/9/11.
//
#import "RBServerLocator.h"
@interface RBServerLocator (Private)
- (void)resolveFirstService;
@end
@implementation RBServerLocator
@synthesize serviceBrowser = _serviceBrowser;
+ (RBServerLocator *)sharedLocator
{
static RBServerLocator *sharedLocator;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedLocator = [RBServerLocator new];
});
return sharedLocator;
}
- (id)init
{
self = [super init];
if (self) {
self.serviceBrowser = [NSNetServiceBrowser new];
self.serviceBrowser.delegate = self;
__foundServices = [NSMutableArray array];
}
return self;
}
- (void)locateServerMatchingType:(NSString *)type completion:(void (^)(NSNetService *))completionBlock
{
[__foundServices removeAllObjects];
if (completionBlock) {
__completion_block = completionBlock;
}
[self.serviceBrowser searchForServicesOfType:type inDomain:@""];
}
#pragma mark - Service Browsing
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
[__foundServices addObject:aNetService];
if (!moreComing) {
[self resolveFirstService];
}
}
#pragma mark - Service Resolving
- (void)resolveFirstService
{
NSNetService *service = [__foundServices objectAtIndex:0];
service.delegate = self;
[service resolveWithTimeout:10.0];
}
- (void)netServiceDidResolveAddress:(NSNetService *)sender
{
if (__completion_block) {
__completion_block(sender);
}
__completion_block = NULL;
}
@end
@implementation NSNetService (RBResolvedURL)
- (NSURL *)RBResolvedURL
{
return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%d/", self.hostName, self.port]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment