2012-03-12 40 views
0

幫助在ios 5中爲瀏覽器應用製作統一的地址欄?所以這裏是我的地址欄。在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]; 
} 

我不能添加一個「其他」引用來說,如果它不是一個地址,那麼附加谷歌搜索標籤?如果是這樣如何?你會知道如何使用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]; 
} 

回答

0

這裏有一些技巧可以幫助你:

  • 使用stringByAddingPercentEscapesUsingEncoding:而不是你的 「+」 替代。
  • 你應該確認http://不是一個前綴URL字符串添加之前
  • 應實現UIWebViewDelegate協議時加載一個無效的URL時出現錯誤識別
  • 則作爲備用發射您的Google搜索(現在您可以用「+」替換「」)...或者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] 
    } 
} 
+0

謝謝你的快速反應。我包含的代碼像在safari中一樣爲2個獨立的文本字段工作。我想知道如何將它們連接到一個。也許這是在回覆中解釋的,但我不知道如何使用它。我不只是想讓別人爲我寫出來,但我對此很陌生,並且還不太瞭解。請提供更多幫助。 – user1264599 2012-03-12 18:54:02

+0

你描述的行爲是你可以通過實施我的提示獲得的行爲。如果(從文本字段開始的文本字段以http://開頭){去到地址} else(追加http://到文本字段的內容並啓動請求; if(request ok){fini}其他{去谷歌與文本字段的內容} – 2012-03-13 11:46:47

+0

因此,他們的文本將以「*。*」的形式添加http://如果文本是「*」或「* * *」,那麼它發送到谷歌搜索。這是否簡單?我說「簡單」,即使我仍然不知道如何寫它 – user1264599 2012-03-13 15:57:28