According to the Apple documentation :
If that service name conflicts with an existing service on the network, Bonjour chooses a new name. ... your service is automatically renamed if it conflicts with the name of an existing service on the network
How can I achieve this function?
My implementation:
self.publishService = [[NSNetService alloc] initWithDomain:@"local." type:@"_http._tcp." name:@"MyName" port:80];
self.publishService.delegate = self;
[self.publishService publish];
- (void)netServiceDidPublish:(NSNetService *)sender {
NSLog(@"did publish: %@", sender.name);
}
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict {
NSLog(@"did not publish: %@", errorDict);
}
When this service is already published the didNotPublish
delegate method will be called. I assume the service won't be published?
I thought that the netServiceDidPublish:
delegate method should be called again for the service with the new name, but it isn't.
The problem here is the port, not the name.
If there is a name collision, it automatically renames the service by appending " (2)"
to the name, increasing the number as far as it needs to. In this case it will publish successfully and call netServiceDidPublish:
.
If the port is already used by another published service it won't publish it, and will call netService:didNotPublish:
with the error dictionary set to NSNetServicesErrorCode = 48; NSNetServicesErrorDomain = 1;
.