Displaying a webpage inside a UIWebView

I am trying to display a simple webpage inside my UIWebView without Nib. The problem is that when I click on my button, a new page blanck page appears, but nothing is displayed. 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,

+4
source share
3 answers

If this is the exact code you use, then it cannot work: the webView is added to the topView, which never fits on the screen anywhere.

You probably want to add a webView to the controller view, but it might be better to do this 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]; } 
+6
source

Using storyboards -

Step 1: Drag and Drop the UIWebView into the View

Step 2: Then go to the .h file (for this particular view) and create an IBOutlet UIWebView. For instance -

 // MainViewController.h @interface MainViewController : UIViewController @property (nonatomic, strong) IBOutlet UIWebView *myWebView; @end 

Step 3. Go to the storyboard and create a connection to the output of myWebView (this can be found in the Xcode inspector area) in the UIWebView by dragging and dropping the control.

Step 4: Now that we have the connection, we just need to go to .m (for this 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 
+6
source

Here is My Solution. Create a ViewController with a WebView in Interface Builder and plug in a webview as an IBOutlet This code is simple and works great

 - (void)viewDidLoad { [super viewDidLoad]; NSURLRequest *request = [NSURLRequest requestWithURL:@"http://www.google.com.ua"]; [webView loadRequest:request]; } 
+2
source

All Articles