亲爱的地球同胞。
我正在请求一个真实的例子,我可以测试我在下面找到的身份验证质询代码段。如果不可能,我会很感激有关如何做的任何建议,以便我可以验证它。
我感觉代码正在运行:
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
NSString *host = webView.URL.host;
NSString *authenticationMethod = [[challenge protectionSpace] authenticationMethod];
if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodDefault]
|| [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
|| [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
NSString *title = @"Authentication Challenge";
NSString *message = [NSString stringWithFormat:@"%@ requires username and password.", host];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Username";
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Password";
textField.secureTextEntry = YES;
}];
[alertController addAction:[UIAlertAction actionWithTitle:@"Authenticate" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *username = ((UITextField *)alertController.textFields[0]).text;
NSString *password = ((UITextField *)alertController.textFields[1]).text;
NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}]];
[_delegate webView:self didReceiveAuthenticationChallengeWithAlertController:alertController];
}
else if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
对所有人的爱与和平。
来源:https://github.com/ShingoFukuyama/WKWebViewTips
旧问题:How can I properly implement an authentication challenge using a WKWebView?
答案 0 :(得分:0)
通常你只需要在代码中设置特定的断点,然后在调试器控制台中用expr varName=@"test"
之类的语句操作一些变量来测试这样的代码。
这里有趣的部分是如何触发对webView:didReceiveAuthenticationChallenge: