Quote:
Originally Posted by BilalBhatti
Hi, i am new to iPhone app development. Need little help in displaying a number which a URL returns.
Suppose i have a URL which returns a random number every-time it is accessed. The content of the resulting page only contains that random number (No HTML code, just number is displayed)
http://example.com/get-random-number/
Output:
55
How can i display this number in my iPhone app? The best possible way?
|
The best way and the easiest way are 2 different things.
The easiest way is to use code like this:
Code:
NSString* urlString = @"http://example.com/get-random-number/";
NSString *resultString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString: urlString]] autorelease];
After you run that code, if the HTTP get succeeds, resultString will contain @"55" (or whatever). You could then use the NSString method intValue to get the integer value of the resultString;
The problem with this code is that it does a synchronous HTTP get. The code will block on the initWithContentsOfURL call until either the server responds or the request fails/times out. This can be as long as 2 minutes - which is (obviously) not a great user experience.
The alternative is to write code that performs the HTTP get asynchronously, using NSURLRequest and NSURLConnection. It changes the solution from 2 lines of code to more like 2
pages of code, but it makes for a much more robust app and a better user experience.
Duncan