How to get http:// address of page loaded in UIWebView? - ios

I have webView and send my cookies to my site for using same session (web store).
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), CGRectGetMaxY(self.view.frame))];
[webView setDelegate:self];
[self.view addSubview:webView];
NSString *sessionId = [[OCRESTAPIClient sharedClient] sessionId];
NSString *value = [#"xid=" stringByAppendingString:sessionId];
NSURL *url = [NSURL URLWithString:#"http://MySite.ru/cart"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:value forHTTPHeaderField:#"Cookie"];
[webView loadRequest:request];
User can walking on my site and i must to know where he is. How can i get web address of loaded page in webView?

Please make your class the delegate of the webview using
webView.delegate = self
Then override the delegate method,
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("current url is \(request.mainDocumentURL!.absoluteString)")
return true;
}
This will give the current url going to be loaded

use UIWebView delegate method
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
self.url = webView.request.mainDocumentURL;
}

Related

Open webview link in another View Controller

I have a webview and I want to open the urls that I can click in that webview in another ViewController for example to change the navigation bar and add a back button.
This is my current code in objective-c:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *fullURL = #"https://www.apple.com/";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
self.webView.delegate = (id)self;
[self.webView loadRequest:requestObj];
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
refreshControl.tintColor = [UIColor clearColor];
[self.webView.scrollView addSubview:refreshControl];
}
-(void)handleRefresh:(UIRefreshControl *)refresh {
NSString *fullURL = #"https://www.apple.com/";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
[refresh endRefreshing];
}
Any solutions?
Thank you!
from UIWebview delegate you should use "shouldStartLoadWith" and check navigationType for linkClicked:
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .linkClicked{
if let url = URL(string:"YourURLString") {
if UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
return false
}
}
}
return true
}
More info about uiwebview delegates can be found here:
https://developer.apple.com/documentation/uikit/uiwebviewdelegate/1617945-webview

WKWebview pass custom header in iOS

I am working on WKWebView for loading some web pages. I need to pass some header inside WKWebView for change of language. I have passed successfully, however on server side, its showing other language. Please let me know whether the mechanism of passing is right or wrong.
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:#""];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(#"%#",navigationAction.request.allHTTPHeaderFields);
NSMutableURLRequest *request = [navigationAction.request mutableCopy];
[request setValue:#"sv" forHTTPHeaderField:#"Accept-Language"];
decisionHandler(WKNavigationActionPolicyAllow);
}
There are two mistakes in your code:
1) You define the header fields too late (after the webview has already started to use the request to load the page)
2) You set the header on a mutable copy of the actual request (so not on the one that's used). This copy is then just dealloced once the method finishes.
Try this here in your viewDidLoad:
// ... start as you did
NSURL *nsurl=[NSURL URLWithString:#""]; // I assume you're using a correct URL in your actual code?
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:nsurl];
[request setValue:#"sv" forHTTPHeaderField:#"Accept-Language"];
[self.view addSubview:webView];
[webView loadRequest:nsrequest]; // I just prefer to add to the view hierarchy before I do anything with it, personal preference.
You do not need to do anything regarding the header fields in your webView:decidePolicyForNavigationAction:decisionHandler: delegate method.

shouldStartLoadWithRequest not working in iOS

I'm trying to override a url with the following code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *urlString = #"http://www.google.com/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[_udazzWebView loadRequest:urlRequest];
NSLog(#"log");
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest: (NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"log2");
//use NSURLRequest object request , to manage the request.
NSURL *urL=request.URL;
NSString *urlStr=[urL absoluteString];
NSLog(#"URLL %#",urlStr);
if([urlStr isEqualToString:#"PostPicPopUp"]){
NSLog(#"log3");
}
return YES;
}
Log2 doesn't appear in the console. I'm guessing it has something to do with replacing NSURLRequest in the viewDidLoad, but I don't know how to do it.
It seems to me you are just missing UIWebView delegates init like
- (void)initWebViewWithRect:(CGRect)rect {
self.webView = [[UIWebView alloc] initWithFrame:rect];
self.webView.backgroundColor = [UIColor whiteColor];
self.webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.webView.opaque=NO;
self.webView.userInteractionEnabled=YES;
self.webView.delegate=self;
[self cleanSubViews];
}
You UIWebView should be defined like
#interface MXMBaseWebView()<UIWebViewDelegate, UIScrollViewDelegate, MXMWebViewProgressDelegate> {
CAGradientLayer *shadowLayer;
MXMWebViewProgressView *_progressView;
MXMWebViewProgress *_progressProxy;
UIRefreshControl *_refreshControl;
}
#property(nonatomic, strong) UIWebView *webView;
#end
so you will do calls like
[self.webView loadRequest: [NSURLRequest requestWithURL:url]];
At this point everything should work properly.

Basic url not working in WebView

I am learing WebView.
when I do something like
NSString *url = #"www.google.com";
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
it fails.
But when I type www.google.com (or even google.com) in standard browser, it works fine.
I also noticed that after loading the page, the url text field in standard browser changes the link from www.google.com to https:// www. google.co.in/?gws_rd=ssl
In above code when I set NSString *url = #"https://www.google.co.in/?gws_rd=ssl" it works fine
So how do I implement my WebView view so that if should work like a standard browser it terms of above context
UIWebView always needs http or https when starting request, if you click on links inside the webView it will handle it itself. So here is how to handle it:
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *addressBar = [[UITextField alloc] init];
[addressBar setDelegate:self];
[self loadRequestFromString:#"www.google.com"];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self loadRequestFromString:textField.text];
[textField resignFirstResponder];
return YES;
}
- (void)loadRequestFromString:(NSString *)urlString
{
NSURL *webpageUrl;
if ([urlString hasPrefix:#"http://"] || [urlString hasPrefix:#"https://"]) {
webpageUrl = [NSURL URLWithString:urlString];
} else if ([urlString containsString:#" "] || ![urlString containsString:#"."]) {
webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com/search?q=%#", [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
} else {
webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#", urlString]];
}
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webpageUrl];
[_webView loadRequest:urlRequest];
}
to open any URL in UIWebView you should add url with protocol
eg #"http://www.google.com".
[NSURL URLWithString:#"http://www.google.com"];
then it will work.

iOS UIWebView detect mixed SSL content

How would you detect any attempt to display an SSL URL that contains non-SSL assets in WebView? Just like a browser gives you a mixed-SSL warning.
I don't see any obvious property on UIWebView or UIWebViewDelegate. I could subclass NSURLProtocol, and somehow communicate the non-SSL connections back to the UIWebView. Is there an easier way to do this?
One solution is to create your custom URL cache and make it the default so you can catch all HTTP requests, and then you can check for mixed SSL content.
Here is an example:
#interface MonitoringURLCache : NSURLCache
#end
#implementation MonitoringURLCache
- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest *)request {
NSURL *requestURL = [request URL];
NSURL *pageURL = [request mainDocumentURL];
if ([[pageURL scheme] isEqualToString:#"https"] && [[requestURL scheme] isEqualToString:#"http"]) {
NSLog(#"Non safe resource: %# referenced from page: %#", requestURL, pageURL);
}
return [super cachedResponseForRequest:request];
}
#end
/// Register your custom cache
MonitoringURLCache *cache = [[MonitoringURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];
/// Make a request to a website with mixed SSL content
NSURL *url = [NSURL URLWithString:#"https://some-website-with-mixed-ssl-content/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];

Resources