NSNetService:发布服务时处理名称冲突

NSNetService: Handle name conflicts when publish service

根据 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

如何实现这个功能?

我的实现:

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);
}

当此服务已发布时,将调用 didNotPublish 委托方法。我假设该服务不会发布?

我认为应该为具有新名称的服务再次调用 netServiceDidPublish: 委托方法,但事实并非如此。

这里的问题是端口,而不是名称。

如果存在名称冲突,它会通过在名称后附加 " (2)" 自动重命名服务,并根据需要增加数量。在这种情况下,它将成功发布并调用 netServiceDidPublish:.

如果该端口已被另一个已发布的服务使用,它将不会发布它,并将调用 netService:didNotPublish: 并将错误字典设置为 NSNetServicesErrorCode = 48; NSNetServicesErrorDomain = 1;