WKWebview pass custom header in iOS - 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.

Related

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

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

UIWebView Image Upload reloading webview Objective c

I am using UIWebview to show user profile details. Now when trying to upload the image whole Webview reloading and showing back to the same stage before uploading.
UIWebView *ProfileCellWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, cell.layer.frame.size.width, (MainFrame.size.height - 210))];
[ProfileCellWebview setBackgroundColor:[UIColor clearColor]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:USERPROFILEPUBLIC,self.appDelegate.currentUser.userId]];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[ProfileCellWebview setDelegate:self];
[ProfileCellWebview loadRequest:requestObj];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[cell addSubview:ProfileCellWebview];
Where i am doing wrong
Implement the code to load the url in viewDidLoad. Hope you write the code in viewWillApear or viewDidApper.

Get current URL in UIWebview but it not respond

I create app to use UIWebview and show log to url if touch in content in UIWebview.
this is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url1 =[NSURL URLWithString:#"MyWebSite"];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
[_webView1 loadRequest:request1];
NSURL *url2 =[NSURL URLWithString:#"MyWebsite2"];
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
[_webView2 loadRequest:request2];//url menu 2
NSString *currentURL = [_webView1 stringByEvaluatingJavaScriptFromString:#"document.title"];
NSLog(#"%#",currentURL);
}
but I touch the content log is not print and change webview log is print (null)
sorry for my poor English.
You can not get title of a website before you receive data from the URL.
So
Set your webview delegate to self
Then in
- webViewDidFinishLoad: to get title

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.

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