Objective-c – Display a webpage inside a UIWebView

objective cuiwebview

I try to display a simple webpage inside my UIWebView without a Nib. The problem is when I click on my buttun a new page blanck page appear but nothing is display.
Did I miss something?


- (void)loadView {

    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.webView = web;

    NSString *urlAddress = @"http://www.google.com";
    NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];


    [webView loadRequest:requestObj];

    [topView addSubview:self.webView];
    [web release];
}

thank you,

Best Answer

If this is the exact code you're using then it can't work: the webView added to topView that is never put on screen anywhere.

You probably want to add the webView to the controller view, but a better place to do that might be viewDidLoad, where self.view can be used safely.

This code works for me:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView = [[[UIWebView alloc]
        initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];

    NSString *urlAddress = @"http://www.google.com";
    NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [self.webView loadRequest:requestObj];

    [self.view addSubview:self.webView];
}