Search code examples
objective-cnsurlconnectionnsmutableurlrequestnsurlconnectiondelegate

How to wait till asynchronous request returns data before returning value


I have send asynchronous request to a website using the following code:

NSMutableURLRequest *requestSiteToSendData = [NSMutableURLRequest requestWithURL:[[NSURL alloc]initWithString:@"www.example.com"] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:30];
NSURLConnection *connectionToSiteToSendData = [[NSURLConnection alloc]initWithRequest:requestSiteToSendData delegate:self];

Then I used the following method defined inside NSURLConnectionDelegate to get and parse the data after the data fetching is completed.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //parse 'data'
    NSString *parsedData = [self parseDataWithData:data];
}

And then in the method in which I send the asynchronous request, I return parsedData. But the returning should only happen after the data fetching is completed and hence parsing is done. I know the question arises if that is what I need then why I am not using synchronous request. It is because I don't want my other methods to hang up when the loading is going on in background.


Solution

  • Quick answer : if it's asynchronous, you don't want to wait the asynchronous method. One of the bests option would be :

    • The object calling wanting the data should set itself as the object that runs the asynchronous method, and in didReceiveData, you call a method such as updateData:(NSString *)parsedData, which handles the newly received data

    • The object calling the method should use KVO to observe any change on a property of the object that runs the asynchronous method.

    Tell me if you need more informations.