Thursday, February 21, 2013

Secure Coding iPhone and iPad Apps

A Simple App Using NSURLConnection

The easiest way to initiate HTTP requests in iOS is to utilize the NSURLConnection class. Here is sample code from a very simple application that takes in a URL from an edit-box, makes a GET request, and displays the HTML obtained.
Please note that the code in this particular example is mostly from Apple's wonderful tutorial on how to use NSURLConnection
//This IBAction fires when the user types in a URL and presses GO
- (IBAction) urlBarReturn:(id)sender
{
//htmlOutput is the UITextView that displays the HTML
htmlOutput.text=@"";
//urlBar is the UITextField that contains the URL to load
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlBar.text]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(!theConnection)
htmlOutput.text=@"failed";
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//receivedData is of type NSMutableData
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString *tempString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
htmlOutput.text = [NSString stringWithFormat:@"%@%@",htmlOutput.text,tempString];
[tempString release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(@"Connection failed! Error: %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
htmlOutput.text=[NSString stringWithFormat:@"Connection failed! Error %@ %@",[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[connection release];
[receivedData release];
}


No comments:

Post a Comment