pabloruiz55
pabloruiz55

Reputation: 1306

retrieving data from url in iphone

i have a php page that connects to a database and retrieves data from a table given a GET parameter, suppose one would retrieve a list of shirts given a color:

select * from shirts where color = $_GET[color ;

I want form the iphone to make a request to that page, (sending that get parameter) and retrieve that data for using it in my app.

How would i do that?

Thanks!

Upvotes: 2

Views: 1016

Answers (2)

Rengers
Rengers

Reputation: 15228

Retrieving data from an URL can be done by using NSURLConnection. You provide this class a NSURLRequest and it will try to fetch the data in the background. Using delegate methods, you can then 'respond' to failures or success.

You can create the NSURLRequest like this:

//color is your color object
NSString *url = [NSString stringWithFormat:@"http://www.yoursite.com/yourpage.php?color=%@",color];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

(More information and an example)

Upvotes: 2

Adam Woś
Adam Woś

Reputation: 2473

The simplest way would be to use

NSString *url = [NSString stringWithFormat:@"http://www.yoursite.com/yourpage.php?color=%@",color];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

because with the NSURLRequest you have to do some more magic to get the actual data.

If you want a NSString from NSData, use

NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// ...
[response release]; // do this somewhere or you'll have a mem-leak!

Upvotes: 1

Related Questions