how to change UIWebView Tap events - iphone

How Can I change the UIWebView tap action Controls.like when I tap and hold on some link in UIWebView ..it opens a UIActionSheet with three options open copy add to reading list ...I need to change this UIActionsheet controls like ..I need to add one more button into this ...how to do that...how to disable this and add new UIActionSheet according to my choice...
code
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [ request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
// Call your custom actionsheet and use the requestURL to do what you want :)
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:#"Contextual Menu"
delegate:self cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil otherButtonTitles:nil];
[sheet addButtonWithTitle:#"Save Page as Bookmark"];
[sheet addButtonWithTitle:#"Open Page in Safari"];
[sheet showInView:webView];
return NO;
}
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]]];
webview.delegate=self;
}
- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == actionSheet.cancelButtonIndex) { return; }
switch (buttonIndex) {
case 0:
{
NSLog(#"Item A Selected");
NSLog(#"reg%#", request);
NSURL *requestURL = [request URL];
[webview loadRequest:[NSURLRequest requestWithURL:requestURL]];
break;
}
case 1:
{
NSLog(#"Item B Selected");
break;
}
}
}

You can do like this , catch a tap on link and use your actionsheet then
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [ request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
// Call your custom actionsheet and use the requestURL to do what you want :)
return NO;
}
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
webview.delegate=self;
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]]];
}

Related

Webview content is not readable after stop animating loading image

I am building one iPhone application where I have two views one for login view and another for web view. When user enters the login credentials, then it will redirect to web view. while loading the webview from login view too much time is taking to load. hence I used alertview to show loading image.
#interface FocusViewController ()
#end
#implementation FocusViewController
#synthesize txtsecurecode;
#synthesize webView;
#synthesize OrganizationCode;
UIActivityIndicatorView *indicator;
UIAlertView *alert;
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (FocusAppDelegate *)[[UIApplication sharedApplication]delegate];
if(appDelegate.data.strOrganizationCode == nil || appDelegate.data.strAccessCode == nil)
{
NSLog(#"YOUR FIRST SCREEN");
_loginView.hidden = NO;
webView.hidden = YES;
}
else
{
NSLog(#"LOAD WEBVIEW DIRECTLY\n");
NSLog(#"Organization Code -> %# \n Secure Access Code -> %#",appDelegate.data.strOrganizationCode,appDelegate.data.strAccessCode);
OrganizationCode.text = appDelegate.data.strOrganizationCode ;
txtsecurecode.text = appDelegate.data.strAccessCode;
[self loginClicked:nil];
webView.hidden = NO;
_loginView.hidden = YES;
}
}
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtsecurecode text] isEqualToString:#""] || [[OrganizationCode text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Access code" :#"Login Failed!":0];
}
else
{
NSString *post =[[NSString alloc] initWithFormat:#"txtsecurecode=%# #&password=%#",[txtsecurecode text],[OrganizationCode text]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/AccountService/security/ValidateAccess?accesscode=%#&companycode=%#&type=1", txtsecurecode.text, OrganizationCode.text]];
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
if([responseData isEqualToString:#""]){
[self alertStatus:#"Please enter valid Access Code" :#"Login Failed !" :0];
}
else
{
appDelegate.data.strOrganizationCode = OrganizationCode.text;
appDelegate.data.strAccessCode = txtsecurecode.text;
[FocusAppDelegate addCustomObjectToUserDefaults:appDelegate.data key:kCredentails];
//Updated
_loginView.hidden = YES;
webView.hidden = NO;
responseData = [responseData stringByReplacingOccurrencesOfString:#" "" " withString:#""];
NSString* encodedString = [responseData stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#" ,encodedString);
alert = [[[UIAlertView alloc] initWithTitle:#"Loading\nPlease Wait..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
indicator.center = CGPointMake(alert.bounds.size.width / 2, alert.bounds.size.height - 50);
[indicator startAnimating];
[alert addSubview:indicator];
[indicator release];
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
webView.delegate = self;
webView.frame = self.view.bounds;
NSString* urlTwo = [[encodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:#"%22" withString:#""];
NSURL *url2;
if([urlTwo hasPrefix:#"http://"]){
url2 = [NSURL URLWithString:urlTwo];
}else{
url2 = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#" , urlTwo]];
}
NSLog(#"url2:%#", url2);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[webView loadRequest:requestObj];
[[self view] addSubview:webView];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!" :0];
}
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(#"webViewDidStartLoad");
[self.view addSubview:self.indicator];
alert.hidden = NO;
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"webViewDidFinishLoad");
[self.indicator removeFromSuperview];
[self.alert dismissWithClickedButtonIndex:1 animated:NO] ;
}
- (IBAction)backgroundClick:(id)sender
{
[txtsecurecode resignFirstResponder];
[OrganizationCode resignFirstResponder];
}
#end
Until content in webview displays, loading image is displaying and working good. but content of webview is not editable and remaining static as I think I used 'web view.hidden = YES'. when I comment the alert method and run then content of webview is also editable and working good as required. I need to load the content of url after loading image stops loading.
I would suggest show the activity indicator from the Viewcontroller having the WebView and implement the WebView Delegate methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[actvityIndicator startAnimating];
}
and
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[actvityIndicator stopAnimating];
}
this will keep your webview Interactive and also show the indicator till the page loads completely
you can try something like this. The Delegate is important in .h file
FocusViewController.h
#interface FocusViewController : UIViewController <UIWebViewDelegate> {
UIActivityIndicatorView *indicator;
}
FocusViewController.m
- (void)viewDidLoad
{
// Loading Indicator
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[indicator setColor:[UIColor colorWithRed:50.0/255.0 green:120.0/255.0 blue:200.0/255.0 alpha:1.0]];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[indicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[indicator stopAnimating];
}

UIWebView does not load the URL

I have very small problem while loading the URL in UIWebView.
I have one UIButton, on clicking of it, I add the UIView which contains UIWebView, UIButton & Title bar. Code used is as follows -
[self.view addSubview:vwOnline];
vwOnline.bounds = self.view.bounds;
//Load webview
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#", objWine.strOnlineURL]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[wbvwOnline loadRequest:request];
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//Show activity indicator
[indicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Remove Activity indicator
[indicator stopAnimating];
[indicator removeFromSuperview];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"Error - %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Find A Vino" message:#"Error while loading request." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag = 1;
//Remove Activity indicator
[indicator stopAnimating];
[indicator removeFromSuperview];
}
By doing above code, most of times the UIWebView does not loads the URL which I passed in the object objWine.strOnlineURL. If I clicked the back button & again clicked on the button to load the URL, it goes into the - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error delegate method of UIWebView.
If anyone knows the solution, then please help me.
Instead of adding your webview on your button click each time. Why don't you add your webview into your viewDidLoad and hide and show it in your button click.
when you are going back, make request to nil and load empty htmlstring to webview. One more thing, remove [indicator removeFromSuperview]; line from
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
-(void)webViewDidFinishLoad:(UIWebView *)webView
use
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
if it is work fine then check objWine.strOnlineURL
otherwise it is clear :)

XCode: How can I check the URL type on every page load in UIWebView?

I need some sample code to check if the page is 'file', 'http' or 'www' on the page load. At the moment the code is as follows;
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:#"file"]) {
[webView loadRequest:request];
[homebutton setHidden:YES];
NSLog(#"Opened File");
return NO;
}
else if ([[URL scheme] isEqualToString:#"http"]) {
[webView loadRequest:request];
[homebutton setHidden:NO];
NSLog(#"Opened External Page");
return NO;
}
else if ([[URL scheme] isEqualToString:#"www"]) {
[webView loadRequest:request];
[homebutton setHidden:NO];
NSLog(#"Opened External Page");
return NO;
}
}
return YES;
}
I want it based around this but this is only when a link is clicked and I want it to apply when a form is filled out and then the form redirects to another page etc...
I would really appreciate a quick answer,
Thank you very much,
James Anderson
Probably you need to check out the various UIWebViewNavigationType listed in the "constants" section here

Creare a custom action for an existing button in a webview

I'm displaying an URL on a webview, and on that page there is a button. How can I customize the action that occurs when that button is pressed?
You controller has to respond to <UIWebViewDelegate>.
Then, override this method:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
NSURL *URL = [request URL];
if ([[URL absoluteString] rangeOfString:#"http://give.it.a.custom.url.to.identify.this.action"].length > 0)
{
// your custom action here
}
return NO;
}
return YES;
}
Don't forget the [youWebView setDelegate:self];.

After authentication through a webview, how do I redirect my application to show app view

I have made an application that logs onto a simple UIWebview login page and then authenticates on the website that loads. The thing is, I want my app to autheticate on the website and as soon as it is authenticated I want it to redirect my app to the view I have made in Xcode. I am fairly new to iphone programming.
Any help would be appreciated.
The code I made so far also consists of cookies, and it looks as follows:
FOR MY APP DELEGATE:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self initPreferences];
// Override point for customization after application launch.
NSArray *siteArray = [[NSArray alloc] initWithObjects:#"http://...com",
#"http://....com",
#"http://...com",
#"http://...com",
#"http://.com",
nil];
SignonWebView *webView = [[SignonWebView alloc] initWithURL:[siteArray objectAtIndex:2]];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(cookieChange:) name:#"NSHTTPCookieManagerCookiesChangedNotification" object:nil];
if ([Constants useAuthenticator])
{
[[self window] addSubview:[webView view]];
}
else
{
[self.window addSubview:navigationController.view];
}
// [self.window makeKeyAndVisible];
// Check for device
if (![self deviceConnected])
{
[Constants setConnectedToDevice:NO];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ALERT!" message:#"Device Not Detected" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert autorelease];
}
else
{
if ([Constants isLineaPro])
{
NSLog(#"Init LineaPro device");
}
else if ([Constants isVerifone])
{
NSLog(#"Init Verifone device");
DeviceControl *dc = [DeviceControl sharedInstance]; // Singleton initializes device
[[dc payControl] hostPowerEnabled:YES];
NSLog(#"---------------------- Sending message to MSR");
[[dc pinPad] sendStringCommand:#"Q40" calcLRC:YES];
}
}
//AdminViewController = [[AdminViewController alloc] init];
[self.window makeKeyAndVisible];
//[self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:0.933 green:0.114 blue:0.149 alpha:1]];
//[[UIApplication sharedApplication] setupScreenMirroringOfMainWindow:navigationController framesPerSecond:20];
//[[UIApplication sharedApplication] setupScreenMirroringWithFramesPerSecond:20];
return YES;
//[self.parentViewController.view setHidden:YES];
}
-(void)cookieChange:(NSHTTPCookieStorage *)somethin
{
NSLog(#"----------- Cookies have changed sucessfully
---------------");
}
FOR MY LOGIN VIEW WHICH HAS COOKIES:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"shouldStartLoadWithRequest");
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(#"webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(#"***************** webViewDidFinishLoad --- getting all cookies");
NSMutableArray *cookieList = [[NSMutableArray alloc] init];
NSHTTPCookie *cookie;
for (cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookieList addObject:cookie];
// NSLog(#"%# expire: %#\n%#", [cookie name],[cookie expiresDate],cookie);
}
NSLog(#"Number of cookies is %d",[cookieList count]);
if (initialLoad)
{
NSLog(#"---- removing existing cookies -----");
for (NSHTTPCookie *currentCookie in cookieList)
{
NSLog(#"Removing cookie : %#",[currentCookie name]);
//[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:currentCookie];
}
initialLoad = NO;
}
else
{
for (NSHTTPCookie *currentCookie in cookieList)
{
NSLog(#"='%#'",currentCookie);
if ([[currentCookie name]isEqual:#"UserID"]) {
// we have a user id returned from services, so save it
[self setUserIDCookie:currentCookie];
NSLog(#" -- userIDCookie : %#",[[self userIDCookie] value]);
[self setUserID:([[self userIDCookie] value])];
}
if ([[currentCookie name]isEqual:#"UserName"]) {
// we have a user id returned from services, so save it
[self setUserNameCookie:currentCookie];
NSLog(#" -- userNameCookie : %#",[[self userNameCookie] value]);
[self setUserName:([[self userNameCookie] value])];
}
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"didFailLoadWithError : %#",error);
}
#pragma mark -
#pragma mark Actions
-(void)loadUrl:(NSString*)URL
{
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL]]];
}
#end
If the authentication is successful, have the server redirect to a certain URL. Then, in webView:shouldStartLoadWithRequest:navigationType:, check for that URL and move to your other view when it is loaded.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"shouldStartLoadWithRequest");
if([[[request URL] absoluteString] isEqualToString:#"http://authSuccess.website.com"]) {
[[[UIApplication sharedApplication] delegate] authenticationSuccessful];
return NO;
}
return YES;
}
And, in the app delegate:
- (void)authenticationSuccessful {
[[[self.window subviews] objectAtIndex:0] removeFromSuperview];
[self.window addSubview:navigationController.view];
}