Question

Help making a Unified address bar in ios 5 for a Browser App? So here is my address bar.

-(IBAction)url:(id)sender {
    NSString *query = [urlBar.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", query]];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
    [webPage loadRequest:request];
}

Couldn't I add an "else" reference to say if it is not an address then append the google search tag? If so how? And would you know how to use Bing instead of google?

-(IBAction)googleSearch:(id)sender {
    NSString *query = [googleSearch.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?hl=en&site=&q=%@", query]];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
    [webPage loadRequest:request];
}
Was it helpful?

Solution

Here are some tips to help you:

  • use stringByAddingPercentEscapesUsingEncoding: instead of your "+" replacement.
  • you should check if http:// is not a prefix to the URL string before adding it
  • you should implement the UIWebViewDelegate protocol to identify when an error occurs when loading an invalid URL
  • then as a fallback launch your Google search (now you can replace " " by "+")... or Bing, whatever and up to you!

Your code should looks something as follow:

...
webView.delegate = self; // Should appear in your code somewhere
...

-(IBAction)performSearch {
    if ([searchBar.text hasPrefix:@"http://"]) {
        ... // Make NSURL from NSString using stringByAddingPercentEscapesUsingEncoding: among other things
        [webView loadRequest:...]
    } else if ([self isProbablyURL:searchBar.text]) {
        ... // Make NSURL from NSString appending http:// and using stringByAddingPercentEscapesUsingEncoding: among other things
        [webView loadRequest:...]
    } else {
        [self performGoogleSearchWithText:searchBar.text]
    }
}

- (BOOL)isProbablyURL:(NSString *)text {
    ... // do something smart and return YES or NO
}

- (void)performGoogleSearchWithText:(NSString *)text {
    ... // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search
    [webView loadRequest:...]
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    ... // Notify user
    if (was not already a Google Search) {
        [self performGoogleSearchWithText:searchBar.text]
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top