objective-c - 在 UIWebView (IOS 5) 中更改用户代理

标签 objective-c ios5 uiwebview user-agent

到目前为止我做了什么:我使用下面的代码更改项目中 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/

相关文章:

ios - 从 swift 调用 objective-C typedef block

iphone - 以编程方式将文本文件从 iPhone 粘贴到网络计算机

objective-c - 自定义 UITableView 不刷新单元格

使用新的 ios sdk 5.0 屏幕锁定后 iPhone 应用程序网络连接断开

iphone - glGenBuffers 和 glGenFramebuffers 和 glGenRenderbuffers 之间有什么区别

ios - 在 iOS 7 中呈现和关闭模态视图

iphone - 播放 iPod 库中的歌曲,仅包含其标题

iOS应用程序中的C++算法

ios - 选择 UITableViewCell 后如何显示 UIWebView?

ios - Swift UIWebView Pdf 查看 UIActivityViewController 错误