如何检测UIWebview在iOS中加载需要身份验证的URL

时间:2014-07-15 10:27:16

标签: ios networking uiwebview nsurlconnection

我制作的iOS应用程序允许2个用户互相交互。当第一个用户使用UIWebView导航到他的应用程序上的URL时,我会将此URL发送给第二个用户。第二个用户收到此链接并使用UIWebView加载它。

在一个人进入私人区域之前一切正常。例如,当第一个用户访问www.google.com并登录到他的Gmail帐户时。现在我捕获此链接并发送给试图加载它的第二个用户,但这失败了,因为它是第一个用户的私有区域。

第二个用户的UIWebView如何知道收到的网址是在私有区域中还是必须通过身份验证才能访问它?

这里有一些插图代码:

在第一个用户上,导航www.google.com等网址时。我称这个函数为

 - (void)loadRequestUrl:(NSString *)url {
       NSLog(@"load request");

       //Load request
       self.websiteUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:websiteUrl]];
      [wbWebview loadRequest:request];

      //Send url to partner
      //I'm using GCDAsyncSocket to send this url string to our server
      //And server will send it to my current partner

      //Just example code for sending
      [asyncSocket send:url];
}

//第二个用户。我收到了GCDAsyncSocket委托的url字符串。在这个委托中,我称之为函数

- (void)receiveUrl:(NSString *)url {

      //Just Load request

      self.websiteUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

      NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:websiteUrl]];

      [wbWebview loadRequest:request];

}

这里是第一个用户登录谷歌帐户后的网址示例 https://accounts.google.com.vn/accounts/SetSID?ssdc=1&sidt=ALWU2cscH%252BVqOOjXXIRKgtz4Q8qmIcJ5lE0dy7xh7MISa%252Bw75BNSeOrF3cO91IED8Cy6PfREuDjuXLzdOMEPaaP0p6XZpCzJFQi4w2xAZa9VKubLQ5xk5%252FF%252FOj8KR0f6e5PSav%252Fww0mKEAuPoI0Dtnve600Pj6PERFtvlH3kbt2Y0hk4KEBpn6nk7zAXUdt2wc%252FaHK0%252FufzyfIMI2hkLpCFu1W1XaOIS3zwuGttA5tXjyLb3AeBLmPgfBbsd7hwZWp7IRVJGglde8gAJ%252F%252BmIhQD4eMQa1s7LD8tnuoagx%252BmRzQ4EGqtcAlE%252FGE3e8b1itkh2HXZQZYB612X1NpcPgta1XbgO7IHd0g7HsDEnsqodhHtr9F7vGl4fO%252BCcHFYaHjH3dT2mCjnOwBn%252Bbh0%252FykYpxqbx2W8K%252BHcZp3B4KI166qCPCZvgnvq7QACPsPuWGVrll4Nw2yLK%252FE2bdmFVILfgIpVbY9SheA%253D%253D&continue=http%253A%252F%252Fwww.google.com.vn%252F%253Fgfe_rd%253Dcr%2526ei%253Dgf7EU-TLL-zV8ge_rYCIAw

第二个用户收到它,但无法打开。我无法捕获任何代表的错误

重要性:我不需要强制第二个用户打开它,我只想捕获事件以告诉第二个用户第一个用户进入私人区域

2 个答案:

答案 0 :(得分:3)

要在uiwebview中接收和处理身份验证质询,请输入以下代码。

- (void)viewDidLoad
{ 

// Load the web view with your url
  [webView loadRequest:[NSURLRequest requestWithURL:[NSURL      URLWithString:@"yoururl"]]];
  isauth = NO;
}

现在为代表们。在将新请求加载到webview之前调用此文件。

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{

  if (!isauth) {
    isauth = NO;
    [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
    return NO;
  }
  return YES;
}


//in nsurlconnections delegate. This one deals with the authentication challenge. this time set isauth to YES

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

  if ([challenge previousFailureCount] == 0) {
    isauth = YES;
    [[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"username" password:@"password"  persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge];
  }
  else
    [[challenge sender] cancelAuthenticationChallenge:challenge]; 
}

// if the authentication is successfully handled than you will get data in this method in which you can reload web view with same request again.

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

  NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL   URLWithString:@"yoururl"]];

  [webView loadRequest:urlRequest];
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
  return NO;
}

希望它有所帮助。

谢谢。

答案 1 :(得分:3)

获取用户名和密码,有多种方法可以做到,你可以创建自己的机制。一种简单的方法就是。

-

(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:    (NSURLAuthenticationChallenge *)challenge{

NSLog(@"Need Authentication");

UIAlertView *webLogin = [[UIAlertView alloc] initWithTitle:@"Auth" 
                                                   message:@"Enter User and Password" 
                                                   delegate:self 
                                                   cancelButtonTitle:@"Cancel" 
                                                   otherButtonTitles:@"OK"
                                                   , nil];

self. challenge = challenge;
webLogin.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[webLogin show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

user = [[alertView textFieldAtIndex:0]text];
pass = [[alertView textFieldAtIndex:1]text];

if (buttonIndex == [alertView cancelButtonIndex]) {

    [self dismissModalViewControllerAnimated:YES];
}
else if (buttonIndex != [alertView cancelButtonIndex]) {

    [self handleChallenge:self.challenge withUser:user password:pass];
}


}

- (void)handleChallenge:(NSURLAuthenticationChallenge *)aChallenge     withUser:(NSString *)userName password:(NSString *)password {

NSURLCredential *credential = [[NSURLCredential alloc]
                               initWithUser:userName password:password
                               persistence:NSURLCredentialPersistenceForSession];
[[aChallenge sender] useCredential:credential forAuthenticationChallenge:aChallenge];

}