从UIWebView中的按钮Xcode 4.3在safari中打开相同的URL

时间:2012-07-14 07:55:35

标签: iphone ios xcode uiwebview

我对Xcode相对较新,我已经开始构建一个使用UIWebView的应用程序。为了使其符合App Store提交的要求,Apple更喜欢使用Safari。为了解决这个问题,我想在我的UIWebView导航中添加一个按钮,单击该按钮将在Safari中打开相同的URL。这个例子可以在Twitter应用程序中看到;他们有一个按钮,可以在Safari窗口中打开当前查看的UIWebView

1 个答案:

答案 0 :(得分:2)

您可以使用UIWebViewDelegate的方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if iWantToOpenThisURLInSafari([request URL]) {
        [UIApplication openUrl:[request URL]];
        return NO; // tell the webView to not navigate to the URL, I'm handling it
    } else {
        return YES;
    }
}

- (BOOL)iWantToOpenThisURLInSafari:(NSURL* url) [
    // you just have to fill in this method.
    return NO;
}

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIWebViewDelegate

编辑:@PaulGraham要求的更多细节

// You have a pointer to you webView somewhere
UIWebView *myWebView;

// create a class which implements the UIWebViewDelegate protocol
@interface MyUIWebViewDelegate:NSObject<UIWebViewDelegate>

// in this class' @implementation, implement the shouldStartLoad..method

@implementation
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if iWantToOpenThisURLInSafari([request URL]) {
        [UIApplication openUrl:[request URL]];
        return NO; // tell the webView to not navigate to the URL, I'm handling it
    } else {
        return YES;
    }
}

// then, set the webView's delegate to an instance of that class

MyUIWebViewDelegate* delegate = [[MyUIWebViewDelegate alloc] init];
webView.delegate = delegate;

// your delegate will now recieve the shouldStartLoad.. messages.