Skip to content

Instantly share code, notes, and snippets.

@rabinjoshi
Created December 9, 2012 20:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rabinjoshi/4246864 to your computer and use it in GitHub Desktop.
Save rabinjoshi/4246864 to your computer and use it in GitHub Desktop.
Loading content in a WebView using NSURLConnection
@implementation RJViewController {
__weak IBOutlet UIWebView *_webView;
NSURLConnection *_urlConnection;
NSMutableData *_receivedData;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = @"http://google.com";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
_urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(_urlConnection) {
_receivedData = [[NSMutableData alloc] init];
}
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failure.");
_receivedData = nil;
_urlConnection = nil;
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %d bytes of data",[_receivedData length]);
[_webView loadData:_receivedData MIMEType:@"text/html" textEncodingName:@"@utf-8" baseURL:nil];
_urlConnection = nil;
_receivedData = nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment