WKWebView使用功能点

本文介绍如何使用WKWebView更改全局User-Agent(UA),并提供了一种通过添加自定义信息来修改UA的方法。此外,还详细说明了如何处理HTTPS认证挑战,包括信任管理和认证流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、更改UA,wk提供了新的属性customUserAgent直接修改,不用下面的如此麻烦

// 更改全局UA,此处修改之后,app内都将使用这个新的UA
User-AgentUIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
 
// 给User-Agent添加额外的信息
NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"new_user_agent"];
 
// 设置global User-Agent
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
 
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

2、https认证

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {    
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
         
if ([challenge previousFailureCount] == 0) { 
            
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];   
          
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);  
       
} else {    
         
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); 
        
}    
 
} else {    
     
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);   
  
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值