UIWebView not getting next Url to Load - ios

I am working on a native cum web iOS app. When i try to load Urls in UIWebView on any button press inside WebView i am unable to get the next URL to be loaded. Can anyone suggest anything for this? Thanks in advance.
Here is my Code:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *myString = [[request URL] absoluteString];
[myString lowercaseString];
NSLog(#"%#",myString)
NSDictionary *headers = [request allHTTPHeaderFields];
BOOL hasReferer = [headers objectForKey:#"X"]!=nil;
if (hasReferer)
{
return YES;
}
else
{
// relaunch with a modified request
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *url = [request URL];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:X forHTTPHeaderField:#"X"];
[request setValue:Y forHTTPHeaderField:#"Y"];
[loadingWebView loadRequest:request];
});
});
return NO;
}
return 0;
}

set delegate
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;
see in this method what it returns
and make sure you are passing correct url ie stringByAddingPercentEscapesUsingEncoding

Related

WKWebView: trouble using evaluateJavaScript from remote URL requiring Basic Auth

I have a remote JavaScript file that I would like to load from WKWebView. The dev Website the JavaScript file is on requires Basic Auth in order to Access.
The JavaScript file needs needs to load as a result of a button.
In otherwords, I can't use the WKUserScript injectionTime options.
I have two code examples. Both of them only half work. I can't test if the auth works without the EvaluateJavascript working, and I can't test the EvaluateJavascript function without the Basic Auth working... so... using WKWebView * webView...
NSString *authStr = #"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: #"Basic %#",[authData base64EncodedStringWithOptions:0]];
NSURL* jsURL = [NSURL URLWithString:#"http://dev.xxxx.com/js/xxxxx.js"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:jsURL];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[_webView loadRequest:request];
I can see the javascript in the webView window, but it is not being evaluated.
Then I have this other strategy:
- (void)handleButton {
NSURL* jsURL = [NSURL URLWithString:#"http://dev.xxxx.com/js/xxxxx.js"];
_scriptString = [NSString stringWithContentsOfURL:jsURL usedEncoding:NSUTF8StringEncoding error:nil];
}
-(void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
if (challenge.previousFailureCount == 0){
NSURLCredentialPersistence persistence = NSURLCredentialPersistenceForSession;
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"username" password:#"password" persistence:persistence];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
NSLog(#"in Auth");
}
else{
NSLog(#"%s: challenge.error = %#", __FUNCTION__, challenge.error);
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(#"navigation complete");
NSLog(#"scriptString %#", _scriptString); //Says UNAUTHORIZED
if ([_scriptString length] > 0) {
[_webView evaluateJavaScript:_scriptString completionHandler:^(NSString *result, NSError *evaluateError) {
if (result == nil) {
NSLog(#"no go dude: %#", evaluateError);
return;
}
NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"i think it worked: #%", data);
}];
}
}
Any help would be greatly appreciated!!
I loaded the javascript URL in Safari on my iPhone, and entered the basic auth username and password into the popup.
Then, this is the code that worked:
NSURL *jsURL = [NSURL URLWithString:#"http://username:password#dev.xxxx.com/js/xxxxxx.js"];
NSString *injectedJS = [NSString stringWithContentsOfURL:jsURL encoding:NSUTF8StringEncoding error:nil];
[_webView evaluateJavaScript:injectedJS completionHandler:nil];

How can I load a local version of a javascript file instead of a remote version?

I want to load a webpage with a huge javascript file.
<script src="js/sample.js"></script>
I cannot change the html file, but i can download the javascript file to my Application.
NSString* path = [NSString stringWithFormat:#"http://www.demo.url/index.html"];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[webView loadRequest:request];
Everytime I start my App the chached javascript file have to reload again. Maybe I have the wrong cache settings.
Two possible solution:
Cache the javascipt in the right way. Do not delete on app close.
Manual download javascript file and use it.
are you trying to inject javascript?
[webView stringByEvaluatingJavaScriptFromString:jsString];
if you are trying to load local html file for the 1st time, add it to the bundle and call it liek this:
NSURL *relativeURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSURL *u = [NSURL URLWithString:#"xxx.html" relativeToURL:relativeURL];
and then when you need to reload you do a normal uiwebview request method call!
I found the solution:
Implement an own NSURL Protocol:
NSURLProtocolCustom.h
#import <Foundation/Foundation.h>
#interface NSURLProtocolCustom : NSURLProtocol<NSURLConnectionDelegate> {
NSMutableData *responseData;
}
#property (nonatomic, strong) NSURLConnection *connection;
#end
NSURLProtocolCustom.m
#import "NSURLProtocolCustom.h"
#implementation NSURLProtocolCustom
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
if ([[request.URL lastPathComponent] isEqualToString:--Your precached file--]) {
return true;
} else {
return false;
}
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
- (void)startLoading {
NSString* file = --Your local file--;
NSData *data = [NSData dataWithContentsOfFile:file];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL] MIMEType:#"text/javascript" expectedContentLength:-1 textEncodingName:nil];
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[self.client URLProtocol:self didLoadData:data];
[self.client URLProtocolDidFinishLoading:self];
}
- (void)stopLoading {
}
And your request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:--your URL-- cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:50.0];
[NSURLProtocol registerClass:[NSURLProtocolCustom class]];

iOS webview connection error handling

I'm trying to load a url . But sometimes it gives a error url in the following delegate method.
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL* url = [request mainDocumentURL];
NSString* absoluteString = [url absoluteString];
NSLog(#"%#",absoluteString);}
I want to know that how can i cancel the current url request and reload a new url ?
try this
if([webView isLoading])
{
[webView stopLoading];
}

How to fill a HTML form using Objective-C

I would like to load a web page (containing a form: username and password) in a UIWebView, but I would like the web page to be filled when the UIWebView is loaded. I read so much stuff and tried so many things, but nothing works.
here is my code :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://login.live.com"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"username" forHTTPHeaderField:#"session[email]"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.webView loadRequest:request];
Let's say you have a form field defined like this:
<input type="text" id="mytext">
Then you can assign a value to this field as follows:
NSString *javascript = #"document.getElementById('mytext').value = 'new value'";
[webView stringByEvaluatingJavaScriptFromString:javascript];
The above code needs to run after your page has fully loaded. For example, you can make your view controller implement UIWebViewDelegate, declare the method - (void)webViewDidFinishLoad:(UIWebView *)webView and do it there.
EDITED: 20/03/2014 -: I added how to get the code from the UIWebView
If you want know when the page did finish loading, you should implement UIWebViewDelegate in your UIViewController:
Then you can detect when the page finish loading by implementing this method:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
[_activityIndicator stopAnimating];
_activityIndicator.hidden = TRUE;
}
In you case, you want to modify the code when the page it's loaded, so in the method (void)webViewDidFinishLoad:(UIWebView *)webView you should do the next to get the code as a NSString:
NSURL *requestURL = [[yourWebView request] URL];
NSError *error;
NSString *page = [NSString stringWithContentsOfURL:requestURL encoding:NSASCIIStringEncoding error:&error];
For more details take a look to this answer.
I hope this help you.

UIWebView Detect mp3 file loading

In my application i have UIWebView and i want to detect if a MP3 file is load(download).
So i use this UIWebView Delegate method:
- (BOOL)webView:(UIWebView*)webview shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
if ([[[url pathExtension] lowercaseString] isEqualToString:#"mp3"]) {
[self userDidClickUrl:url];
return NO;
}
return YES;
}
The problem is that sometimes the URL is without mp3 string inside,and the UIWebView open the Native player. It's possible to detect it? I want to detect when a mp3 file is start loading.
Try to detect MIMEType based on your request - check if MIMEType from response is either one of those kind:
audio/mp3 || audio/mpeg3 || audio/x-mp3 || audio/x-mpeg3
Update: check this already answered:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = request.URL;
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
[conn start];
return YES; }
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSString *mime = [response MIMEType];
NSLog(#"%#",mime); }
Full link bellow:
UIWebView Delegate get MIME Type

Resources