简体   繁体   中英

How to read TXT records with apple bonjour for iOS

I tried to get TXTrecords in didFindService function, but I found the value is null.

Have you any idea to resolve my problem?

- (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser didFindService:(NSNetService*)service moreComing:(BOOL)moreComing {
    [self.services addObject:service];

    NSDictionary* dict = [[NSNetService dictionaryFromTXTRecordData:[service TXTRecordData]] retain];
    MyTreeNode *node = [[MyTreeNode alloc] initWithValue:[service name]];
    NSString* info = [self copyStringFromTXTDict:dict which:@"info"];
    if([info isEqualToString:@"child"]) { // info == null and dict == null??
        [treeNode addChild:node];
    }
    [info release];
    if (!moreComing) {
        [self sortAndUpdateUI];
    }
}

You need to resolve the service first. In the callback you have there all you know is the service exists, but you don't have its records (neither its A nor its TXT).

You can use -resolveWithTimeout: to resolve it. You can also use -startMonitoring if you need to get notified when the TXT record is modified.

I changed my didFindService function as follows (My application is based on the example of Apple "BonjourWeb") :

- (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser didFindService:(NSNetService*)service moreComing:(BOOL)moreComing {
    [self.services addObject:service];
    NSInteger i,n = [self.services count];
    for(i=0;i<n;i++)
    {
        NSLog(@"%d %@",i,[[self.services objectAtIndex:i]name]);
        if (self.currentResolve) {
            [self stopCurrentResolve];
        }
        self.currentResolve = [self.services objectAtIndex:i];
        [self.currentResolve setDelegate:self];
        [self.currentResolve resolveWithTimeout:0.0];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(showWaiting:) userInfo:self.currentResolve repeats:NO];
    }

    if (!moreComing) {
        [self sortAndUpdateUI];
    }
}

I noticed in running my application, the function netServiceDidResolveAddress is called one time and it resolve only the last element of the array self.services (I have 11 services, it solves only the object that has the index 10). My problem is to have all the services resolved.

My problem is resolved here is the final code:

- (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser didFindService:(NSNetService*)service moreComing:(BOOL)moreComing {
    [service setDelegate:self];
    [service resolveWithTimeout:0.0];
    [self.services addObject:service];

    if (!moreComing) {
        [self sortAndUpdateUI];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM