Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a webpage inside a UIWebView

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,

like image 629
ludo Avatar asked Dec 10 '22 18:12

ludo


2 Answers

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];
}
like image 142
duncanwilcox Avatar answered Jan 31 '23 11:01

duncanwilcox


Using the Storyboard -

Step 1: Drag and drop a UIWebView in the View

Step 2: Then go to the .h file (for that particular view) and create an IBOutlet of a UIWebView. For example-

// MainViewController.h

@interface MainViewController : UIViewController

      @property (nonatomic, strong) IBOutlet UIWebView *myWebView;

@end

Step 3: Go to the storyboard and create a connection from outlet, myWebView (This can be found in the inspector area of Xcode) to the UIWebView by doing a control drag.

Step 4: Now when we have the connection, we just need to go to the .m (for that particular view) and add the following code -

//MainViewController.m

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *urlNameInString = @"https://www.google.com";
    NSURL *url = [NSURL URLWithString:urlNameInString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    [self.myWebView loadRequest:urlRequest];
}

@end
like image 34
Natasha Avatar answered Jan 31 '23 10:01

Natasha