How to detect java script in UIWebView - iphone

In a web page i have two select box, after select a value from first select box the second select box if fill by java script or may be Ajex. but in my UIWebView the second select box is not fill. so please help me. this is work well in safari web browser.
- (void)viewDidLoad {
[super viewDidLoad];
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
}
-(void)webViewDidStartLoad:(UIWebView *) portal {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)webViewDidFinishLoad:(UIWebView *) portal{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSString *userInfo = [[error userInfo] objectForKey:NSURLErrorFailingURLPeerTrustErrorKey];
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],userInfo);
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:userInfo delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil,nil];
[alerView show];
[alerView release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

You should turn on the Debug Console in your mobile safari and look if there java script errors, else you should debug through with alerts.
Turn on Debug Console:
Open Settings -> Safari -> Developer (At the bottom) -> Debug Console on|off

Related

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 :)

UIWebView only calls didFailLoadWithError once

I have a native iPhone app that just loads a website using UIWebView. I implemented the UIWebViewDelegate function didFailLoadWithError to display an error message when the user attempts to use the app without an Internet connection. The alert box shows up the first time I build and run the app, but does not appear thereafter. If I click the home button, then tap my app again, I just see a blank UIWebView. It's as if it's not trying to load the page again, so it never triggers didFailLoadWithError. This is just a simple app without saving and reloading of state, so shouldn't reloading the app re-run all my code, including the attempted loading of the website?
- (void)viewDidLoad {
NSString* urlString = [NSString stringWithString:#"http://www.site.com"];
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
[super viewDidLoad];
}
#pragma mark UIWebView delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//[myActivityIndicatorView stopAnimating];
NSLog([NSString stringWithFormat: #"%d", [error code]]);
if ([error code] != USER_STOPPED_LOAD) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Connection Error!"
message:#"You must be connected to the Internet to use Site."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
No because it only gets sent to the background when you click the Home button! To restart the app, kill it using the multitasking bar.

App crashes due to WebView

In my app I am using UIwebview to display websites, however whenever I click back button and start playing with other parts in the app, the app mostly crashes with no reason. I suspect the webview is causing this issue because it crashes only when I try to open the webview.
I have used NSURLConnection to load the webview and have made webview, connection objects to nil in the view will Disappear method.
#implementation NewsWebSiteViewController
#synthesize connection,rcvdData,spinner1,currentSite,webView,newsWebsite;
- (void)viewDidLoad {
[super viewDidLoad];
#try {
self.webView.delegate=self;
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
self.title= self.newsWebsite.title;
self.webView.backgroundColor =[UIColor groupTableViewBackgroundColor];
self.spinner1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect center = [self.view bounds];
CGSize winCenter = center.size;
CGPoint pont = CGPointMake(winCenter.width/2,winCenter.height/2);
[spinner1 setCenter:pont];
[self.view addSubview:spinner1];
[self.spinner1 startAnimating];
NSString *url = newsWebsite.link;
NSURLRequest *theReq =[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
self.connection = [[NSURLConnection alloc] initWithRequest:theReq delegate:self];
if(self.connection) {
self.rcvdData = [[NSMutableData data] retain];
}
else {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error!" message:#"We are having a problem connecting to the internet, why not try again or try sometime later!.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
webView.multipleTouchEnabled=YES;
webView.scalesPageToFit=YES;
}
#catch (NSException * e) {
}
}
-(void) goBack {
self.webView =nil;
[self.navigationController popViewControllerAnimated:YES];
}
-(void) viewWillDisappear:(BOOL)animated {
[self.connection cancel];
self.connection=nil;
[self.webView stopLoading];
self.webView=nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
}
-(void) webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
}
-(void) viewDidAppear:(BOOL)animated {
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.rcvdData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.rcvdData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
[connection release];
[rcvdData release];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error!" message:#"We are having a problem connecting to the internet, why not try again or try sometime later!.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
[rcvdData release];
NSString *url = newsWebsite.link;
NSURL *url1 = [NSURL URLWithString:url];
[self.webView loadData:self.rcvdData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:url1];
}
- (void)dealloc {
[super dealloc];
[self.spinner1 release];
}
#end
Firstly, here's a small primer to equality/inequality in C/Objective-C:
Let's say you have a BOOL value (ie, a value that can be either YES or NO, 'On' or 'Off', 'True' or 'False'), called isEnabled. Now, if I had assigned this BOOL value (sometimes called a 'flag') to 'YES', I could conditionally test its value like so:
BOOL isEnabled = YES;
if (isEnabled)
{
// value set to yes
}
In addition to the above, I can use the negation operator (an exclamation mark - otherwise known as the NOT operator) to flip isEnabled's value, and test its opposite value:
BOOL isEnabled = YES;
// the following reads as "if is *not* enabled"
if (!isEnabled)
{
// value set to no
}
now of course in the above example isEnabled is set to YES, so the condition will fail. But, if we consider the following example, the property of if whereby if an else if is 'met' (ie, true) anywhere in a series of if's and else if's, it will execute all the code inside it, and then ignore anything else:
BOOL isEnabled = NO;
if (isEnabled)
{
// any code here will not run, as the above if condition will be false
}
else if (!isEnabled)
{
// this code will run, since the above condition (!isEnabled) will evaluate to true
}
else if (isEnabled)
{
// this code could never run, since the previous condition was true and all following else if's are ignored
}
else if (!isEnabled)
{
// this code could never run, since the previous condition was true and all following else if's are ignored
}
while the above has two redundant else if's at the end, it is a good way to demonstrate how conditional code works.
So, in your webViewDidFinishLoad: method, instead of having a blank if to evaluate an if/else condition, you can replace that with a simpler condition:
-(void) webViewDidFinishLoad:(UIWebView *)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
// or, (self.spinner1 != nil)
if (!self.spinner1)
{
[self.spinner1 stopAnimating];
}
}
When you've made the above change to all your if's and else if's, post a stack trace and I'll see what else it could be.

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];
}

XCode webview connection/server error handling

All,
I am fairly new to XCode and am trying to get a handle on how to best deal with connection issues when trying to use a WebView. I know there are related questions on SO, but none seem to offer complete solutions. I have the following code, but it seems a little inefficient. Hopefully, someone can help me refactor it down to a point where it can be usable anywhere that a UIWebView is called.
NOTE: Please ignore memory issues for now. I realize that has to be added as well.
- (void)viewDidLoad {
[webView setDelegate:self];
NSString *urlAddress = #"http://www.somesite.com/somepage";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[super viewDidLoad];
}
// Check for URLConnection failure
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:#"Connection error" message:#"Error connecting to page. Please check your 3G and/or Wifi settings." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionError show];
webView.hidden = true;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//Check for server error
if ([httpResponse statusCode] >= 400) {
UIAlertView *serverError = [[UIAlertView alloc] initWithTitle:#"Server error" message:#"Error connecting to page. If error persists, please contact support." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[serverError show];
webView.hidden = true;
//Otherwise load webView
} else {
// Redundant code
NSString *urlAddress = #"http://somesite.com/somepage";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
webView.hidden = false;
}
}
// Seems redundant since we are already checking the URLConnection
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:#"Connection error" message:#"Error connecting to page. Please check your 3G and/or Wifi settings." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionError show];
}
I guess what I'm wondering is, are there any shortcuts to achieve the desired functionality? Can I somehow access the URLResponse via the WebView directly? Does a nil value for the URLConnection or UIWebView imply connection errors without having to explicitly check for them? Is there an easier way to pass the URLRequest down into the delegate methods so it doesn't have be recreated twice?
Thanks in advance!
- (void)viewDidLoad {
webView = [[UIWebView alloc]init];
[webView setDelegate:self];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://yourUrl.com"]]]
[super viewDidLoad];
}
#pragma mark UIWebView delegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//read your request here
//before the webview will load your request
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
//access your request
webView.request;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//access your request
webView.request;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"could not load the website caused by error: %#", error);
}
-(void)dealloc{
[webView release];
[super dealloc];
}
You can load the webpage with NSURLRequest directly into your webview. With the delegate callback methods you can change the behavior of your webview.
With this piece of code you should get it done.