In this tutorial we will see how view webpage in our application. If we want to load web pages from within our application, we must embed a web browser in our application through the use of the UIWebView. Using Web view, we can send a request to load web content. The following Try It Out shows how to use the Web view to load a Web page.
TRY IT OUT Loading a Web Page Using the Web View
1 Using Xcode, create a new View-based Application project and name it UsingViews2.
2 Double-click the UsingViews2ViewController.xib fi le to edit it using Interface Builder.
3 In the View window, add a Web View from the Library. In the Attributes Inspector window for the Web view, check the Scales Page to Fit property.
4 In the UsingViews2ViewController.h fi le, declare an outlet for the Web view:
#import@interface UsingViews2ViewController : UIViewController { IBOutlet UIWebView *webView; } @property (nonatomic, retain) UIWebView *webView; @end
5 In Interface Builder, connect the webView outlet to the Web view.
6. In the UsingViews2ViewController.m file, add the following statements that appear in bold:
#import “UsingViews2ViewController.h”
@implementation UsingViews2ViewController
@synthesize webView;
- (void)viewDidLoad {
NSURL *url = [NSURL URLWithString:@”http://www.apple.com”];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];
[super viewDidLoad];
}
- (void)dealloc {
[webView release];
[super dealloc];
}
7. Press Command-R to test the application on the iPhone 4 Simulator. You should see the application
loading the page from Apple.com.
How It Works
To load the Web view with a URL, you first instantiate an NSURL object with a URL via the URLWithString method:
NSURL *url = [NSURL URLWithString:@”http://www.apple.com”];
You then create an NSURLRequest object by passing the NSURL object to its requestWithURL: method:
NSURLRequest *req = [NSURLRequest requestWithURL:url];
Finally, you load the Web view with the NSURLRequest object via the loadRequest: method:
[webView loadRequest:req];
Categories:


