Im using the UIWebView to access a mobile website from within my iPhone application. I need help adding the forward and back navigation buttons. Im really new to this so if someone could provide some good details I would really appreciate your help.
Here is what I have:
UIWebView *webView1 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 480, 251)];
[contentView addSubview:webView1];
webView1.alpha = 1.0;
webView1.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[webView1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.logsitall.com/m"]]];
webView1.scalesPageToFit = YES;
[webView1 release];
contentView.frame = self.view.bounds;
[self.view addSubview:contentView];
[contentView release];
}
- (void)viewDidUnload {
[self setWebView:nil];
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:animated];
}
#end
Final code:
//header
#interface MywebsiteViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIWebView *aWebView;
}
#property (nonatomic, retain) UIWebView *aWebView;
#end
//implementation
- (void)viewWillAppear:(BOOL)animated {
self.aWebView.delegate = self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *myURL = [NSURL URLWithString:#"http://www.WebSiteToLoad.com"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[aWebView loadRequest:myRequest];
}
#pragma mark UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
//show indicator while loading website
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//turn off indicator and display the name of the website in the navBar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.title = [webView stringByEvaluatingJavaScriptFromString:#"document.title"];
}
There are a lot of UIWebView tutorials on.....wait for it....The Web! That said, as I recall, it's as simple as calling goForward or goBack on your WebView:
[[self mainWebView] goForward];
Related
I'm trying to load any URL, after the initial load, in Safari. With any other webpage, this code works fine:
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = [request URL];
if (UIWebViewNavigationTypeLinkClicked == navigationType)
{
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
But as soon as I head over to m.youtube.com, the code no longer does anything, and YouTube continues to load inside the UIWebView. I can't find anything about this online. Any help?
Here is my entire .m file:
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize topLayer = _topLayer;
#synthesize layerPosition = _layerPosition;
#synthesize webView = webView;
#define VIEW_HIDDEN 260
- (void)viewDidLoad
{
[super viewDidLoad];
webView.delegate = self;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://m.youtube.com"]]];
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
webView.scrollView.bounces = NO;
webView.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
[self performSelector:#selector(makeTick)];
self->promoteImages.contentSize = CGSizeMake(1920, 101);
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Scroll3.png"]];
[self->promoteImages addSubview:imageView];
[promoteImages setShowsHorizontalScrollIndicator:NO];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
#end
And here's my .h file for the View Controller:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <Social/Social.h>
#interface SecondViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIScrollView *promoteImages;
NSTimer *time;
IBOutlet UIWebView *webView;
}
#property (nonatomic, nonatomic) UIWebView *webView;
#property (weak, nonatomic) IBOutlet UIView *topLayer;
#property (nonatomic) CGFloat layerPosition;
#property(nonatomic,readonly,getter=isDragging) BOOL dragging;
#end
Here's the code that I use:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
Here's your problem:
[[UIApplication sharedApplication] openURL:url];
Change to:
[[UIApplication sharedApplication] openURL:request.URL];
You can also specify only certain URLs to open in Safari, for example any URLS beginning with http://www.example.com/share as shown here:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ((navigationType == UIWebViewNavigationTypeLinkClicked) && ([currentURL hasPrefix:#"http://www.example.com/share"])) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
}
In my app I am using TapDetectingWindow to detect touches on a UIWebView (exactly as detailed on http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way).
I used it in one View Controller as suggested with a reference in the header file and the following in the implementation file like
- (id)init {
self = [super init];
if (self) {
tapDetectingWindow = (TapDetectingWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0]; //mWindow, variable reference to TapDetectingWindow
tapDetectingWindow.viewToObserve = webView;
tapDetectingWindow.controllerThatObserves = self;
webView = [[UIWebView alloc] init];
[webView setFrame:CGRectMake(0, 0, 340, 1900)];
[webView setTag:1];
[webView addSubview:keyboardText];
[webView setUserInteractionEnabled:NO];
[webView setDelegate:self];
[webView setOpaque:0.0];
[webView loadHTMLString:htmlString baseURL:NULL];
[self.view addSubview:webView];
keyboardText = [[UITextField alloc] init];
keyboardText.autocorrectionType = UITextAutocorrectionTypeNo;
[keyboardText setDelegate:self];
[self.view addSubview:keyboardText];
}
return self;
}
but my app is crashing at
"tapDetectingWindow.viewToObserve = webView "
with a report * -[UIWindow setViewToObserve:]: unrecognized selector sent to instance 0x4a26b90
Can Any one help me out ...
The problem is not in the above code. Its due to new property introduction in iOS 5.0 with name window under UIApplicationDelegate protocol.
Change your window name in appdelegate file.
In .h file
#class WebViewController;
#class TapDetectingWindow;
#interface test_touchAppDelegate : NSObject <UIApplicationDelegate>
{
TapDetectingWindow *myWindow;
WebViewController *viewController;
}
#property (retain, nonatomic) TapDetectingWindow *myWindow;
#property (retain, nonatomic) WebViewController *viewController;
#end
In .m file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.myWindow = [[TapDetectingWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[WebViewController alloc] init];
self.myWindow.rootViewController = self.viewController;
[self.myWindow makeKeyAndVisible];
return YES;
}
Hope this will help.
what Apurv told you is correct and work like a charm. I see you ask for alternate method to recognise gestures on a webview (I assume that it means click on UIWebView.). The answer is yes, you have to use " UIWebView delegate method ".
#pragma mark -
#pragma mark uiwebview delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if(navigationType==UIWebViewNavigationTypeLinkClicked){
NSURL *URL = [request URL];
if(URL){
[[UIApplication sharedApplication] openURL:URL];
return NO;
}
}
return YES;
}
The code above, when you click on UIWebView, it will open the link of UIWebView that you clicked. Good luck.
I've to switch a part of my app: I will implement a web view insread of a picture (imageview).
So I tried to make it with the interface builder but there is too many errors so I prefer to use code!
for the pictures, I user those lines :
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
self.imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0,64,320,367);
[self.view addSubview:imageView];
[self.imageView release];
Now, I tried to use this code but nothing's showed:
#property (nonatomic, retain) IBOutlet UIWebView *webView;
...
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.fr"]]];
[self.view addSubview:webView];
If you know how to make .... would be nice for me,
THANKS!
Declare in your h file:
UIWebView *contentWebView;
And also tell to your viewController that you will implement <UIWebViewDelegate>
In viewDidLoad Add:
contentWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
contentWebView.delegate = self;
contentWebView.multipleTouchEnabled = YES;
contentWebView.scalesPageToFit = NO;
[self.view addSubview:contentWebView];
In dealloc don't forget to release the webView:
[contentWebView release];
And implement the delegate methods:
#pragma mark -
#pragma mark WebViewDelegates
- (void)webViewDidStartLoad:(UIWebView *)webView{
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}
And also you need to load an request. You can doit in viewDidLoad after you have added the webView to your view:
[contentWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]]];
adjust the frame as u needed and if add anything like imageview as subview to webview then u have to use bringsubviewtofront function.
- (void) initUIWebView {
NSLog(#"DetailViewController->initUIWebView {");
UIWebView *aWebView;
// init and create the UIWebView
aWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
aWebView.autoresizesSubviews = YES;
aWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
//set the web view delegates for the web view to be itself
[aWebView setDelegate:self];
//Set the URL to go to for your UIWebView
NSString *urlAddress = #”http://www.google.com”;
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//load the URL into the web view.
[aWebView loadRequest:requestObj];
//add the web view to the content view
[self.view addSubview:aWebView];
[aWebView release], aWebView = nil;
}
- (void)viewDidLoad {
[self initUIWebView]; // <<<<<<<<<<<< this calls the UIWebView Function
[super viewDidLoad];
}
I am loading some file from document directory using UIWebView. I have set the delegate of UIWebView and I am responding to 2 methods of delegate that is
webViewDidStartLoad and webViewDidFinishLoad I am receiving the webViewDidStartLoad But I am not receiving webViewDidFinishLoad method.
Below is the code:
#interface MyView: UIViewController <UIWebViewDelegate> {
UIWebView *webView;
}
#property (nonatomic, retain) UIWebView *webView;
========================= Class ===========================
-(void)viewDidLoad {
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
mWebView = [[UIWebView alloc] initWithFrame:webFrame];
mWebView.delegate = self;
mWebView.scalesPageToFit = YES;
[self.view addSubview:mWebView];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", pathString]];
[mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];
}
// Delegate methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"start");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"finish");
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Error for WEBVIEW: %#", [error description]);
}
Please let me know what is going wrong. I am not getting any error in didFailLoadWithError delegate method.
Note:- the file that I am loading are huge say 3 MB.
Thanks
=============EDITED==================
As I was loading very huge File the delegate was coming after very long duration that I was not able to notice but for small files everything is working fine
Hey probably you should do this,
-(void)viewDidLoad {
//webView alloc and add to view
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
mWebView = [[UIWebView alloc] initWithFrame:webFrame];
mWebView.delegate = self;
mWebView.scalesPageToFit = YES;
[self.view addSubview:mWebView];
//path of local html file present in documentsDirectory
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", pathString]];
//load file into webView
[mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];
//show activity indicator
[self showActivityIndicator]
}
Call removeLoadingView method in the following UIWebViewDelegate methods
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[self removeLoadingView];
NSLog(#"finish");
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[self removeLoadingView];
NSLog(#"Error for WEBVIEW: %#", [error description]);
}
The showActivityIndicator method
-(void) showActivityIndicator
{
//Add a UIView in your .h and give it the same property as you have given to your webView.
//Also ensure that you synthesize these properties on top of your implementation file
loadingView = [UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]
loadingView.alpha = 0.5;
//Create and add a spinner to loadingView in the center and animate it. Then add this loadingView to self.View using
[self.view addSubView:loadingView];
}
The removeLoadingView method
-(void) removeLoadingView
{
[loadingView removeFromSuperView];
}
Well, does your webview actually finish loading? You should implement the webView:didFailLoadWithError:, too to catch failures.
Since you're not getting either the failure or success message. There might be something wrong with the data that you're trying to load.
Try telling the webView to load an HTML string ("Hello World!"), and see if that succeeds. If it does, then the problem is with your data resource or the path to it.
WebView Delegates
Download MBProgessHUD
Add to your Project
When the page begins load loading (*) progess started and hide after page loaded successfully
.h file
#interface WebViewViewController : UIViewController <MBProgressHUDDelegate, UIWebViewDelegate>
{
MBProgressHUD *HUD;
}
.m File
- (void)webViewDidStartLoad:(UIWebView *)webView
{
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = #"Loading";
[HUD show:YES];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[HUD hide:YES];
}
Probably it is experiencing an error. Implement –webView:didFailLoadWithError: and check.
Make sure to implement the delegate ( ) in the view's .h file and connect the delegate to the view. This fixed it for me.
.h file
#property (retain, nonatomic) IBOutlet UIWebView *webview;
.m file
-(void)viewDidLoad {
NSString *urlAddress = #"YOUR_URL";
_webview.scalesPageToFit = YES;
//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];
}
- (void)webViewDidStartLoad:(UIWebView *)webView;
{
[self.indicater_web startAnimating];
}
//a web view starts loading
- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
[self.indicater_web stopAnimating];
}
//web view finishes loading
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
{
[self.indicater_web stopAnimating];
}
- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)rq
{
[self.indicater_web startAnimating];
return YES;
}
Is it possible to access iphone's camera from uiwebview? I know phonegap does it, but how to make it work without phonegap?
Thanks.
You can implement the UIWebView Delegate and intercept any attempted page load. By setting a custom url, you can pass a message to Objective C, that can launch the camera. To send data back to the web weiw you can initiate a new load (as I do in my example), or pass in some javascript using another method on UIWebView.
Here is a working example, I just wrote:
#import "WebViewCamAppDelegate.h"
#import <UIKit/UIKit.h>
#interface uiwebviewcameraAppDelegate : NSObject <UIApplicationDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIWebViewDelegate> {
UIWindow *window;
UIViewController *viewController;
UIWebView *webView;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
#implementation uiwebviewcameraAppDelegate
#synthesize window;
//This is the HTML we initially show in the WebView. Note the url "showcamera:" is one I
//invented with the intent to intercept it to show the camera.
static NSString *htmlString = #"<br>Show Camera";
//Pretty Basic stuff. We set the UIWebView Delegate so we can intercept the call and set up //a ViewController so we can animate the UIImagePicker
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
viewController = [[UIViewController alloc] init];
webView = [[UIWebView alloc] initWithFrame:window.bounds];
[webView loadHTMLString:htmlString baseURL:nil];
webView.delegate = self;
[viewController.view addSubview:webView];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
//Note: I check to make sure the camera is available. If it is not (iPod touch or Simulator) I show the photo library instead.
-(void) showCamera {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else {
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
imagePicker.delegate = self;
[viewController presentModalViewController:imagePicker animated:YES];
}
//Here we intercept any time the webview tries to load a document. When the user hits our "showcamera: url" we go to work.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqualToString:#"showcamera"]) {
[self showCamera];
return NO;
}
return YES;
}
//After the imagepicker has done it's thing, we pass the data back to the webview to be displayed.
//If we wanted to be fancy here, we could have done this via Javascript so we could dynamically insert an image without reloading the page.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[viewController dismissModalViewControllerAnimated:YES];
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
[webView loadData:imageData MIMEType:#"image/jpeg" textEncodingName:#"UTF-8" baseURL:nil];
}
- (void)dealloc {
[viewController release];
[webView release];
[window release];
[super dealloc];
}
#end