帮助在iOS 5中为浏览器应用程序进行统一地址栏?所以这是我的地址吧。

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

我不能添加“else”参考,说如果它不是地址,那么请附加谷歌搜索标记?如果是这样的话?你会知道如何使用Bing而不是谷歌吗?

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

有帮助吗?

解决方案

以下是帮助您的一些提示:

  • 使用stringByAddingPercentEscapesUsingEncoding:而不是您的“+”替换。
  • 在添加它之前,您应该检查http://是否不是前缀字符串之前的前缀
  • 您应该实现UIWebViewDelegate协议以识别在加载无效URL时发生错误
  • 时发生错误 然后作为一个逆向启动你的谷歌搜索(现在你可以替换“+”)......或bing,无论如何和奉献给你!

您的代码应该如下看起来如下:

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top