Yang Jie Domodomo
Yang Jie Domodomo

Reputation: 685

iOS UIWebView - restricting HTML path

I have an UIWebview and it's loading a particular website section (news). And I want to block the users to access other part of the site, meaning they should only stay in the news section / reading the pdf articles.

I've constructed a set of code, but sadly unable to test them out just yet due to some technical constraint. Will only be able to access it next week. However, I thought it will be a good time to ask here and let the advance user view my draft code and see if its feasible.

- (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"];

Should I use

    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];
    }

}

Or this set of code?

    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]];
    }

And is there any problem with the code? if yes, please point out why it wouldn't work as I'm still in learning phase. Would be a great opportunity to learn more at this stage. The logic I'm looking for is it will load the initial news section. UIWebView should only display the news section / PDF articles from there. If the user try to go to other path, it should detect the current url and redirect them back to news section.

Upvotes: 1

Views: 1046

Answers (1)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

To restrict the load of certain url do the following

webView.delegate = self;

And add the following function

- (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
}

Upvotes: 4

Related Questions