Question

I'm developing an application which is connecting to another device and in order to connect to it my app has to find the IP of it. I'm doing it through UDP socket. I'm sending a message to the server application in the other device and then the server app sends me another message but after I receive it I only use the IP address. Then I want to get it from this .m file to another .m file which is going to make the TCP connection between the two devices. Here's the code I use:

    NSString *SearchCommand = @"AT+S";
static int receivedByteCount = 0;
BOOL       connectedThroughUDP;
- (void) activate {
    connectedThroughUDP = NO;
    AsyncUdpSocket *udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    [udpSocket bindToPort:1234 error:nil ];
    [udpSocket enableBroadcast:YES error:nil];

    NSData* data=[SearchCommand dataUsingEncoding:NSUTF8StringEncoding];

    if ([udpSocket sendData:data toHost:@"255.255.255.255" port:30100 withTimeout:3 tag:0])
    {
        //2 second timeout. onUdpSocket methods will provide results
        [udpSocket receiveWithTimeout:2 tag:0];
        NSLog(@"Connected.");
    }
}

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
    NSString *receiveddata = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    addressOfServer = host;
    NSLog(@"addressOfServer = %@", addressOfServer);
    connectedThroughUDP = YES;
    return YES;
}

- (NSString *) getHost {
    return addressOfServer;
}

- (BOOL) isItConnected {
    return connectedThroughUDP;
}

addressOfServer is global variable.

In the Log when I want NSLog(@"addressOfServer = %@", addressOfServer); I receive the IP address which I want but then when I want to access it from the getHost method I receive (null).

I know it will be something very simple but it caused me a real headache in the past 3 hours so I would be very thankful if you can help me!

Was it helpful?

Solution

Are you calling these 3 lines right after each other like so:

UDPConnection *udpConnection = [[UDPConnection alloc] init];     
[udpConnection activate];     
host = [udpConnection getHost];

If so your issue is that [udpConnection activate]; is going to take some time to connect and figure out the address. You are calling [udpConnection getHost]; too soon.

You will need to setup a delegate or completion block that will be triggered when didReceiveData is fired

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top