views:

197

answers:

2

I have created the following method in cocoa:

-(NSArray *)latestData
{
    NSURL *requestingURL = [NSURL URLWithString:@"someRestfulURL"];

    NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:requestingURL];
    [theRequest setHTTPMethod:@"GET"];

    NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];

    if(theConnection)
    {
     webData = [[NSMutableData data]retain];
    }
    else
    {
     NSLog(@"the connection is NULL");
    }
    return someArray;
}

The RESTful webservice I am calling returns XML that I parse using NSXMLParser.

How can I return an array when calling latestData if I have to wait for the delegate methods of NSURLConnection and NSXMLParser to finish before I can fill the array with the appropriate data?

+1  A: 

Few things you can do 1. Make the request synchronous, this way you will have the array at the time of return. 2. If you want to make it asynchronous, instead of returning the array, have the array as a class member and fill it in the finishedRequest delegate method.

Daniel
I understand that making a synchronous request call will return NSData, but how could I pass this data to my parser and still return an array within the method??
zPesk
Assuming your response is XML or Json , you can do [[NSString alloc] initWithData: encoding:] in order to g et your text back, then you can parse that
Daniel
If you are doing a simply get you can also use NSString *response=[NSString stringWithContentOfURL: url] to get your response synchronously
Daniel
thanks for your help
zPesk
+1  A: 

[NSXMLParser parse] doesn't return until parsing is finished, so that already has the behavior you want, and NSURLConnection has sendSynchronousRequest:returningResponse:error: for synchronous requests.

If you are running this on your main thread though, you should really consider whether you can instead make your method asynchronous instead, as blocking the UI on a network request can make for poor user experience.

smorgan
How would I do it asynchronously and still return an array?? I am having a class request this method so is a class level variable, for the array in the above method, really viable??
zPesk
You would take a delegate argument, and have the delegate implement a known callback method that takes an array.
smorgan
How would this be done?? Is there acode example you couldprovide me??
zPesk
Cocoa is full of examples of this; the NSURLConnection call in your own sample code above is one, and sheets are another.
smorgan