【问题标题】:Emulate mobile Safari in OS X app WebView在 OS X 应用程序 WebView 中模拟移动 Safari
【发布时间】:2011-09-30 12:45:38
【问题描述】:

我正在尝试制作一个 OS X 应用程序,它使用基本的 webview 代码显示移动网站的 WebView,问题是我希望这个 WebView 自动加载它所在的任何网站的移动版本。

 WebFrame *mainFrame = [web1 mainFrame];
NSURL *url = [NSURL URLWithString:@"http://www.website.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[mainFrame loadRequest:request]; 

所以我的问题是,我是否可以在上述代码中添加任何内容,以使此 Web 视图向其所在网站的服务器识别为移动浏览器,从而自动加载任何网站的移动版本它开着?我已经尝试在网上为自己寻找答案,但没有找到答案。

提前感谢您的任何帮助!

【问题讨论】:

    标签: objective-c macos cocoa safari webview


    【解决方案1】:

    是的

    使用NSMutableURLRequest 而不是简单的NSURLRequest,因此您可以对其进行更改并使用其setValue:forHTTPHeaderField: 方法将“User-Agent”HTML Header 字段设置为 MobileSafari 的 User-Agent。

    // You may adapt the UserAgent string depending on what device and Safari version you want to represent
    static NSString* const kMobileSafariUserAgent = @"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:kMobileSafariUserAgent forHTTPHeaderField:@"User-Agent"];
    [mainFrame loadRequest:request]; 
    

    对于要使用的用户代理字符串,它取决于您要“模拟”的 MobileSafari 版本(您想让服务器相信您是哪个版本/设备)。

    See here 可能是一些 UA 字符串

    【讨论】:

    【解决方案2】:

    一个更简单的方法是set that in the WebView

    【讨论】:

    • iOS上好像没有setCustomUserAgent方法
    • @dsokurenko:iOS 没有这个问题所涉及的公共 WebKit 框架。它唯一的 WebKit 公共 API 是 UIKit 中的 UIWebView 类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多