在Objective-C中检测URL是否与我的网站不同

时间:2017-03-09 15:20:25

标签: ios objective-c

我有一个Objective-c应用程序,可以在加载应用程序时打开我的网站。

我网站上的大部分链接指向不同的网站/网址。

我正在尝试更新我的Objective-C代码,如果URL不同,我的网站会在safari浏览器中打开URL,而不是在我的APP中打开。

这甚至可能吗?

这是我的代码

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Load the url into the webview
    NSURL *url = [NSURL URLWithString:@"http://mywebsite.com/"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

2 个答案:

答案 0 :(得分:1)

您希望实施UIWebViewDelegate,具体而言:

- (void)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type {
    if (![request.url.host isEqualToString:@"mywebsite.com"]) {
        [UIApplication.sharedApplication openURL:request.absoluteURL];
        return NO;
    }
    return YES;
}

快速

func webView(webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType navType: UIWebViewNavigationType) -> Bool {
    if request.url?.host != "mywebsite.com" {
        UIApplication.shared.openURL(request.absoluteURL)
        return false
    }
    return true
}

答案 1 :(得分:1)

您需要实现UIWebView的委托并使用:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

     if (navigationType == UIWebViewNavigationTypeLinkClicked) {
         NSString *url = request.URL.host;

         if([url rangeOfString:@"http://mywebsite.com"].location == NSNotFound) {
            [[UIApplication sharedApplication] openURL:request.URL];
            return NO;
         }
         return YES;
      }

      return YES;

}