views:

628

answers:

1

I am trying retrieve data from a .php file on a server from within an iPhone OS app. In one method, I employ the following code:

NSString *aString = [[NSString alloc] initWithContentsOfURL:aURL encoding:anEncoding error:nil];

//See what I got
NSLog(aString);

When I run the App it seems like the App runs through the code so fast I doubt that there was enough time for a Data Request to have transpired. The resulting string is totally empty, which further supports my suspicions. What is happening here? Is the app not waiting for the -initWithContentsOfURL to retrieve data from the .php file on my server? If the app does not wait for this method, is there another method I can use to perform a Data Request in a manner that WAITS for the request to be completed before moving onto the next code?

(I've also read a little on NSURLConnection -- is this maybe what I should be looking into instead of -initWithContentsOfURL?)

+1  A: 

NSURLConnection is great for getting a file from the web... It doesn't "wait" per se but its delegate callbacks:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

...allow you to be notified when data has been received and when the data has been completely downloaded. This way you can have the App show (if you like) a UIProgressBar as the data comes in and then handle the file as you please when it is completely received.

tmh
these methods will only be called in case of a call using NSURLConnection and only when you are making asynchronous calls. The initWithContentsOfURL: will make a synchronous call
lostInTransit