到目前为止我做了什么:我使用下面的代码更改项目中 UIWebView 中的 User-Agent。
NSDictionary *userAgentReplacement = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent",nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userAgentReplacement];
问题:我可以使用这段代码,但是当我再次调用该函数以将 UserAgent 更改为其他内容时,UIWebView 不会更新。为了成功更新 UserAgent,我需要删除/释放 UIWebView 并再次分配/显示它,但这会导致 UIWebView 丢失所有历史记录。有什么方法可以在不创建新的 UIWebView 的情况下更新 UserAgent 使其生效?
最佳答案
当您使用 NSUserDefaults 时,我假设您将它们设置为
application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
我之前使用的替代方法是
NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
[webView loadRequest:request];
您还可以使用 UIWebView 委托(delegate)通过 NSString 变量捕获 webview 的最后加载状态
-(void)webViewDidFinishLoad:(UIWebView *)webView{
currentConfig=[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML];
}
然后使用重新加载 webView
[webView loadHTMLString:currentConfig baseURL:yourURL];
关于objective-c - 在 UIWebView (IOS 5) 中更改用户代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078055/