هل تريد إنشاء شريط بحث عن عنوان موحد في iOS 5؟
-
12-12-2019 - |
سؤال
هل تساعد في إنشاء شريط عناوين موحد في نظام التشغيل 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];
}
ألا يمكنني إضافة مرجع "آخر" لأقول أنه إذا لم يكن عنوانًا، فقم بإلحاق علامة بحث Google؟إذا كان الأمر كذلك كيف؟وهل تعرف كيفية استخدام Bing بدلاً من 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];
}
المحلول
هذه بعض النصائح لمساعدتك:
- يستخدم
stringByAddingPercentEscapesUsingEncoding:
بدلاً من استبدال "+". - يجب عليك التحقق مما إذا كان http:// ليس بادئة لسلسلة عنوان URL قبل إضافتها
- يجب عليك تنفيذ
UIWebViewDelegate
بروتوكول لتحديد متى يحدث خطأ عند تحميل عنوان URL غير صالح - ثم كإجراء احتياطي، قم بتشغيل بحث Google (يمكنك الآن استبدال " " بـ "+")...أو بنج، مهما كان الأمر متروك لك!
يجب أن يبدو الكود الخاص بك كما يلي:
...
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]
}
}
لا تنتمي إلى StackOverflow