欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 修改UserAgent

程序员文章站 2022-05-09 13:25:06
...

WKWebView


//获取UserAgent
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
[wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
    DLog(@"userAgent :%@", result);
}];

//修改UserAgent

NSString *newUserAgent = [userAgent stringByAppendingString:@" 12345678"];
self.webView = [[WKWebView alloc] init];
self.webView.navigationDelegate = self;
[self.webView setCustomUserAgent:newUserAgent];

UIWebView


//获取UserAgent
UIWebView * v = [[UIWebView alloc] init];
[v stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

//修改UserAgent,一定要写在application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)方法中才会生效
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":@"CustomUserAgent-UIWebView"}];
[[NSUserDefaults standardUserDefaults] synchronize];


通过比较两种设置方案,还是用WKWebView更加灵活稳定。毕竟从iOS 8开始就已经作为替代UIWebView的方案,iOS13这都快出了。另外更新的是SFSafariViewController,这玩意完全是调用了Safari浏览器,功能更强大。但是引用苹果官方文档的说法,如果想自定义的话需要用WKWebView:

  • If your app lets users view websites from anywhere on the Internet, use the
    SFSafariViewController class. If your app customizes, interacts with, or controls the display of web content, use the WKWebView class.

  • When you adopt SFSafariViewController and a user presses a link to peek at and then pop to the link’s destination, the user views web content from within your app. Tapping Done, the user returns to the view controller that was displayed before the web content was loaded. When you instead use the WKWebView class, Peek and Pop sends the user to Safari by default.