问题
I'm developing a browser. I need to open new browser windows in the same WKWebView instance, but also I need to be able opening links in Appstore application.
- (void)webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if (navigationAction.targetFrame == nil) {
NSURL *url = navigationAction.request.URL;
UIApplication *app = [UIApplication sharedApplication];
if ([app canOpenURL:url]) {
[app openURL:url];
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark - WKUIDelegate
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
the problem is that it opens all new windows in Safari app. How can I understand if UIApplication is going to open link in Safari app?
回答1:
Well, basically, you can´t distinguish this, as App Store links could be https:// links.
Example Link: https://itunes.apple.com/de/app/myLeetApp/id313370815?mt=8
Apple suggests to just use openURL:
as you´re doing above. See https://developer.apple.com/library/ios/qa/qa1629/_index.html
If you really really want to distinguish them and do something more fancy (e.g. using StoreKit like this: Possible to show a "in App Store modal" in iOS 6?), you´ve got no other option than to parse every link with a regex like so:
import UIKit
let url = "https://itunes.apple.com/de/app/myLeetApp/id313370815?mt=8"
if url.rangeOfString("itunes.apple.com") != nil {
let pattern = "^https?:\\/\\/itunes\\.apple\\.com\\/.*id([0-9]*).*$"
if let regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: nil) {
let extractedAppID = regex.stringByReplacingMatchesInString(url, options: nil, range: NSMakeRange(0, countElements(url)), withTemplate: "$1")
}
}
With the extractedAppID
you then can open the SKStoreProductViewController
etc.
来源:https://stackoverflow.com/questions/29056854/how-can-i-understand-if-uiapplication-is-going-to-open-link-in-safari-app