开发者

Emulate mobile Safari in OS X app WebView

I am trying to make an OS X app that displays a WebView of a mobile website using basic webview code, pr开发者_StackOverflow中文版oblem is I want this WebView to automatically load the mobile versions of whatever website it's on.

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

So my question is, is there anything that I can add to the above code to make this web view identify itself to the server of what ever website it is on as a mobile browser, thus automatically loading the mobile version of any website it is on? I have already tried looking for the answer to this for myself online and haven't had the least bit of luck finding the answer.

Thank you in advance for any and all help!


Yes

Use an NSMutableURLRequest instead of a simple NSURLRequest, so you can alter it and use its setValue:forHTTPHeaderField: method to set the "User-Agent" HTML Header field to the User-Agent of MobileSafari.

// 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]; 

For the User-Agent String to use, it depends on the version of MobileSafari you want to "emulate" (which version/device you want to make the server belives you are).

See here for some of the UA strings possible


A simpler way would be to just set that in the WebView.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜