iOS版的UIWebView - 限制HTML路径(iOS UIWebView - restric

2019-10-16 19:30发布

我有一个UIWebView中和它的加载特定网站部分(新闻)。 我想阻止用户访问网站的其他部分,这意味着他们应该只停留在新闻栏目/阅读PDF格式的文章。

我已经构建了一套代码,但遗憾的是无法测试出来,只是还没有由于一些技术上的限制。 只能下周访问它。 但是,我认为这将是一个很好的时间在这里提出,让高级用户查看我的代码草案,并看看它是可行的。

- (void)viewDidLoad
{   
    [super viewDidLoad];

    NSString *urlAddress = @"http://www.imc.jhmi.edu/news.html";
    NSURL *url =[NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];

    //finding current url and lead it back if it strayed off
    NSString *currentURL = webView.request.URL.absoluteString;
    NSRange range1 = [currentURL rangeOfString:@"news"];
    NSRange range2 = [currentURL rangeOfString:@"pdf"];

我应该使用

    if (range1.location ==NSNotFound){
    currentURL = @"http://www.imc.jhmi.edu/news.html";
    [webView reload];
    }else if (range2.location ==NSNotFound){
    currentURL = @"http://www.imc.jhmi.edu/news.html";
    [webView reload];
    }

}

或这组代码?

    if (range1.location ==NSNotFound){
    currentURL = @"http://www.imc.jhmi.edu/news.html";
    url = [NSURL URLWithString:currentURL
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    }else if (range2.location ==NSNotFound){
    currentURL = @"http://www.imc.jhmi.edu/news.html";
    url = [NSURL URLWithString:currentURL
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    }

并有与代码的任何问题吗? 如果是,请指出,我现在还在学习阶段,为什么它不会工作。 将是一个很好的机会,学习更多在这个阶段。 我在寻找的逻辑是将加载初始新闻栏目。 一个UIWebView只应该从那里显示新闻部/ PDF文章。 如果用户尝试去其他路径,应该检测当前的URL,将用户重定向回到新闻栏目。

Answer 1:

为了限制某些网址的负荷做以下

webView.delegate = self;

而添加的功能

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
     NSString *urlString = [[request URL]absoluteString];
     if(ulrString == @"restricted ur")
          return NO;   //Restrict
     else
          return YES;  //Allow
}


文章来源: iOS UIWebView - restricting HTML path