Thursday, March 17, 2011

UIWebView

In this tutorial, we will open the Google home page in an UIWebView object.In this tutorial, we will open the Google home page in an UIWebView object.



We start by adding a new view to the project. Drag and drop an UIWebView control on the view. As always, create an controller to handle the view, I have named the view and the view controller “WebView” and “WebViewController” respectively. We create a new object of type UIWebView and also declare an associated property. We will use this object to connect “WebView” view placed on the view. This is how the header file will look like
FileName: WebViewController.h
@interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}
@property (nonatomic, retain) UIWebView *webView;
@end
In the implementation file, do not forget to synthesize and release the object’s memory. We then implement viewDidLoad method and this is how it will look like
FileName: WebViewController.m
- (void)viewDidLoad {
NSString *urlAddress = @”http://monaxos.blogspot.com”;
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
NSURL class is used to create an object which will hold the URL information. NSURLRequest is used to create a request to the URL. Method loadRequest of UIWebView is used to load the request in the UIWebView.
With some four lines of code, we can open up pages on the iPhone without using safari.
However, we do need to tell the application to load our “WebView” view when the application is finished launching.
WebViewTutorialAppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.wvTutorial = [[WebViewController alloc] initWithNibName:@”WebView” bundle:[NSBundle mainBundle]];
[window addSubview:[wvTutorial view]];
// Override point for customization after app launch
[window makeKeyAndVisible];
}
Conclusion
The iPhone SDK makes it really easy to use a UIWebView object in an app. This is a good way to display your product web page in the app and not launch safari.

That´s it. Happy programming!

No comments:

Post a Comment