Avoid UIWebView load iTunes App

*爱你&永不变心* 提交于 2020-02-24 12:00:37

问题


How to avoid an UIWebView from opening the iTunes App when loading an iTunes URL?

Example URL: http://itunes.apple.com/nl/app/bluppr-postcards/id348147229?mt=8

Above URL loads the iTunes App directly. UIWebViewDelegate doesn't seem to be able to control this to just load the page in the UIWebView.

It seems it's controlled by the JavaScript function detectAndOpenItunes(); in the body tag of the page.

Any ideas?


回答1:


You're right that the relevant function is detectAndOpenItunes(), which is contained in this file and requires 'iPhone' or 'iPod' to be in the user agent string. I wrote a quick little test app with a web view that just does the following upon viewDidLoad:

[webView loadRequest:
      [NSURLRequest requestWithURL:
        [NSURL URLWithString:
          @"http://itunes.apple.com/nl/app/bluppr-postcards/id348147229?mt=8"]]];

As you say, that opens the App Store app. So I modified it to:

// set some user agent that doesn't have 'iPod' or 'iPhone' in the name
[[NSUserDefaults standardUserDefaults] 
             registerDefaults:[NSDictionary 
                        dictionaryWithObject:@"some old phone or other" 
                        forKey:@"UserAgent"]];

[webView loadRequest:
      [NSURLRequest requestWithURL:
        [NSURL URLWithString:
          @"http://itunes.apple.com/nl/app/bluppr-postcards/id348147229?mt=8"]]];

That displays the page as a web page without opening the app, but there's a problem with the formatting, the displayed page being far too wide. Do a quick search for var deviceDetect= and you'll see that the user agent is also used to determine formatting.

The only solutions I can come up with for that essentially involve screen-scraping-level behaviour. You may subclass NSURLProtocol and add any protocol handler you like via +registerClass:. If you design your protocol to perform HTTP requests then it'll replace the built-in methods for handling HTTP requests. By being selective in which requests you accept or decline, you can do real loading by allowing the HTTP requests you don't want to fall down to the real protocol handler. Hence, you can selectively catch and alter any fetched file before allowing it to be passed to the web view.

You could use that to catch and edit whichever bits of .js and .html you like, but then you're pretty much bound to encounter problems whenever Apple adjust their page.

Similarly, you could use webview's stringByEvaluatingJavaScriptFromString: to execute suitable Javascript to reformat the page after loading, but I'm unable to determine exactly what you'd run and your solution would be just as fragile.



来源:https://stackoverflow.com/questions/6150088/avoid-uiwebview-load-itunes-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!