Monday, June 3, 2013

UIWebView loadData example in Objective C (iOS).

UIWebView loadData

Sets the main page contents, MIME type, content encoding, and base URL.

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

Parameters of [UIWebView loadData]
The content for the main page.
The MIME type of the content.
The IANA encoding name as in utf-8 or utf-16.
The base URL for the content.

UIWebView loadData example.
- (void)viewDidLoad

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];

NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
webView = [UIWebView alloc] init];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

[super viewDidLoad];

Example of [UIWebView loadData].
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        webdata = [[NSMutableData alloc] init];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webdata appendData:data];

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [mWebView loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];

UIWebView loadData example.

CGRect frame = CGRectMake(50,50,0,0);
frame.size = [UIImage imageNamed:@"anim.gif"].size;
NSData *gif = [NSData dataWithContentsOfFile:
    [[NSBundle mainBundle] pathForResource:@"anim" ofType:@"gif"]];
// view
UIWebView *view = [[UIWebView alloc] initWithFrame:frame];
[view loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

End of UIWebView loadData example article.