iossocketsudpcocoaasyncsocket

Receiving UDP broadcast data


I'm trying to receive broadcast UDP datagrams on iOS. I started to use the CocoaAsyncSocket library which seems pretty good. I'm using it like this:

m_socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[m_socket setIPv6Enabled:NO];

NSError* error = nil;
if (![m_socket enableBroadcast:YES error:&error])
    return log_warn(@"Failed to enable broadcast: %@.", error.description);
if (![m_socket bindToPort:43211 error:&error])
    return log_warn(@"Failed to bind to port: %@.", error.description);
if (![m_socket beginReceiving:&error])
    return log_warn(@"Failed to begin receiving.");

The result is that the didReceiveData callback seems not to be called. I therefore tried to use regular socket API and it seems I can get some bytes: I simply used this code.

I am curious about why the CocoaAsyncSocket code above is not working. I tried to compare the two approaches by reading the internals of CocoaAsyncSocket but I'm still not able to find which difference is causing no byte to arrive. Am I missing something in the above code using CocoaAsyncSocket?


Solution

  • By reading the code in CocoaAsyncSocket I see that the member holding the reference to the delegate is weak. Therefore the reason why no callback and no error were received was that the delegate was freed. Storing a strong reference to the object was sufficient to get the data.