I am using CocoaAsyncSocket , I need to make a function which sends a message to the server and wait until the server replies, in delegate methods it does receive server response but I need the function that is sending the message wait for the server to reply and return response.
- (NSString *)sendMessage:(NSString *)message{
NSError *err = nil;
if (![socket connectToHost:@"192.168.1.20" onPort:52523 error:&err]) // Asynchronous!
{
NSLog(@"Error is : %@", err);
}
[socket readDataWithTimeout:-1 tag:1];
NSData* data =[message dataUsingEncoding:NSUTF8StringEncoding];
[socket writeData:data withTimeout:-1 tag:1];
NSString *xmlString = [[NSString alloc] init];
// Here I need the function wait and receive the response
return xmlString;
}
If you need to send something synchronously why not build a request and use NSURLConnection api like here:
This will block until you get a response.
If you want to keep using the async socket approach but forcibly make it a synchronous call you can do this by adding the following methods:
…
…
Now make your method like this
Now in your CocoaAsyncSocket callback socket:didReadData:withTag: and socket:didDisconnectWithError: make sure you call
Once you call that the waiting method will continue, and you’ve just make an asynchronous call synchronous.