【问题标题】:Change User-agent in UIWebView (IOS 5)在 UIWebView (IOS 5) 中更改用户代理
【发布时间】:2012-12-14 05:21:28
【问题描述】:

到目前为止我所做的:我使用下面的代码在项目中更改UIWebView中的User-Agent。

NSDictionary *userAgentReplacement = [[NSDictionary alloc]           initWithObjectsAndKeys:userAgent, @"UserAgent",nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userAgentReplacement];

问题:我的代码可以正常工作,但是当我再次调用该函数以将 UserAgent 更改为其他内容时,UIWebView 不会更新。为了成功更新 UserAgent,我需要删除/释放 UIWebView 并再次分配/显示它,但这会导致 UIWebView 丢失所有历史记录。有什么方法可以更新 UserAgent 而无需创建新的 UIWebView 使其生效?

【问题讨论】:

    标签: objective-c ios5 uiwebview user-agent


    【解决方案1】:

    当您使用 NSUserDefaults 时,我假设您正在设置它们

    application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    

    我以前使用的替代方法是

    NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    [webView loadRequest:request];
    

    您还可以使用 UIWebView 委托来使用 NSString 变量捕获 webview 的最后加载状态

    -(void)webViewDidFinishLoad:(UIWebView *)webView{
        currentConfig=[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML];
    }
    

    然后重新加载 webView 使用

    [webView loadHTMLString:currentConfig baseURL:yourURL];
    

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多