开发者

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开发者_StackOverflow中文版 app.

How would i do that?

Thanks!


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)


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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜