How to Call Https Url in UIwebview (Swift)

How to call https url in uiwebview (swift)?

i find a way to do this,but i think this is not a good way.

step 1------use NSURLConnection in override func viewDidLoad(){} section
request = NSURLRequest(URL:url)

    let urlConnection:NSURLConnection = NSURLConnection(request: request, delegate: self)!

step 2------ use the NSURLConnection delegate to

func connection(connection: NSURLConnection, didFailWithError error: NSError){
println("didFailWithError")
}

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool{
println("canAuthenticateAgainstProtectionSpace")
//return [protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];
return true
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge){
println("did autherntcationchallenge = \(challenge.protectionSpace.authenticationMethod)")

//if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && challenge.protectionSpace.host == "myDomain.com" {

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
println("send credential Server Trust")
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)

}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{
println("send credential HTTP Basic")
var defaultCredentials: NSURLCredential = NSURLCredential(user: "username", password: "password", persistence:NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(defaultCredentials, forAuthenticationChallenge: challenge)

}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM{
println("send credential NTLM")
if challenge.previousFailureCount > 0 {
//如果连续两次验证未通过,则终止, 还需要返回自定义出错界面
//handle bad credentials scenario
}

var defaultCredentials: NSURLCredential = NSURLCredential(user: "username", password: "password", persistence:NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(defaultCredentials, forAuthenticationChallenge: challenge)
}

} else{
challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)
}
//challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)
//challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

/*
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {

}*/
func connection(connection: NSURLConnection, didCancelAuthenticationChallenge challenge: NSURLAuthenticationChallenge){
println("didCancelAuthenticationChallenge")
}
/*
- (void)connection: (NSURLConnection *)connection willSendRequestForAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}*/

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){
println("-----received response");

// remake a webview call now that authentication has passed ok.

//_authenticated =YES;

//[_webloadRequest:_request];
webView.loadRequest(request)

// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)

//[_urlConnectioncancel];
}

it can work

sorry for my poor english skill

How to call https url in uiwebview?

I have explained below how to access https url in UIWebview it will help you clear the problem because it works for me.

Calling http is same as https url.

If, however, you're using a self-signed certificate, it's necessary to add some additional code.Because by default iOS will reject all untrusted https connections.

Restricting untrusted connections is very good default behaviour and any disabling of this is highly risky.So we will show an alert as we're going to bypass the default behaviour.

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

These two above methods allows us to provide our own authentication mechanism for trusted connections

#import "ClassCon.h"
// For now, I've hard coded the IP address of my trusted server.
#define TRUSTED_HOST @"192.168.1.2"

@implementation ClassCon {
NSMutableData *contentData;
NSURLConnection *conn;
}

-(void) loadContent {
contentData = [NSMutableData data];
NSString *contentURL = @"our url";
conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:[NSURL URLWithString:contentURL]] delegate:self];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[contentData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Bad: %@", [error description]);
ContentResponse *response = [[ContentResponse alloc]initWithRc:-999 andDescr:@"error" andAction:0];

conn = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *loadedContent = [[NSString alloc] initWithData:
contentData encoding:NSUTF8StringEncoding];
NSLog(@"Loaded content: %@",loadedContent);

}

// ------------ ByPass ssl starts ----------
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:
(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust];
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge {
if (([challenge.protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust])) {
if ([challenge.protectionSpace.host isEqualToString:TRUSTED_HOST]) {
NSLog(@"Allowing bypass...");
NSURLCredential *credential = [NSURLCredential credentialForTrust:
challenge.protectionSpace.serverTrust];
[challenge.sender useCredential:credential
forAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
// -------------------ByPass ssl ends

@end

Hope this helps

How to load URL in UIWebView in Swift?

loadRequest: is an instance method, not a class method. You should be attempting to call this method with an instance of UIWebview as the receiver, not the class itself.

webviewInstance.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")!))

However, as @radex correctly points out below, you can also take advantage of currying to call the function like this:

UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.ca")!))   

Swift 5

webviewInstance.load(NSURLRequest(url: NSURL(string: "google.ca")! as URL) as URLRequest)

UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible?

Finally I got it!

What you can do is this:

Initiate your request using UIWebView as normal. Then - in webView:shouldStartLoadWithRequest - we reply NO, and instead start an NSURLConnection with the same request.

Using NSURLConnection, you can communicate with a self-signed server, as we have the ability to control the authentication through the extra delegate methods which are not available to a UIWebView. So using connection:didReceiveAuthenticationChallenge we can authenticate against the self signed server.

Then, in connection:didReceiveData, we cancel the NSURLConnection request, and start the same request again using UIWebView - which will work now, because we've already got through the server authentication :)

Here are the relevant code snippets below.

Note: Instance variables you will see are of the following type:

UIWebView *_web
NSURLConnection *_urlConnection
NSURLRequest *_request

(I use an instance var for _request as in my case it's a POST with lots of login details, but you could change to use the request passed in as arguments to the methods if you needed.)

#pragma mark - Webview delegate

// Note: This method is particularly important. As the server is using a self signed certificate,
// we cannot use just UIWebView - as it doesn't allow for using self-certs. Instead, we stop the
// request in this method below, create an NSURLConnection (which can allow self-certs via the delegate methods
// which UIWebView does not have), authenticate using NSURLConnection, then use another UIWebView to complete
// the loading and viewing of the page. See connection:didReceiveAuthenticationChallenge to see how this works.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);

if (!_authenticated) {
_authenticated = NO;

_urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];

[_urlConnection start];

return NO;
}

return YES;
}

#pragma mark - NURLConnection delegate

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"WebController Got auth challange via NSURLConnection");

if ([challenge previousFailureCount] == 0)
{
_authenticated = YES;

NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];

} else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
NSLog(@"WebController received response via NSURLConnection");

// remake a webview call now that authentication has passed ok.
_authenticated = YES;
[_web loadRequest:_request];

// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
[_urlConnection cancel];
}

// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

I hope this helps others with the same issue I was having!

Why some Https url are not loading in the WebView?

Try this :

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{
return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSArray *trustedHosts = [NSArray arrayWithObjects:@"mytrustedhost",nil];

if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
if ([trustedHosts containsObject:challenge.protectionSpace.host]) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

UIWebView won't load links with certificate (https:// prefix)

Fixed my issue, I was able to load https with no problem with the following code I didn't think this would work but it does!:

NSURLRequest *req = [NSURLRequest requestWithURL:mURL];
urlConnection=[[NSURLConnection alloc] initWithRequest:req delegate:self];
webView.scalesPageToFit = YES;
[webView loadRequest:req];

Swift UIWebView not loading http sites

This is due to the App Transport Security, a new protocol introduced by Apple at WWDC 2015. It doesn't allow any connections that are not HTTPS. You can disable it, however it's not recommended as it secures your app.

To disable it you have to edit the App's .plist. Simply right-click the .plist file and select Open As -> Source File and add the following code:

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>

This will allow HTTP requests.

Hope that helps, Julian.



Related Topics



Leave a reply



Submit