<p>有時(shí), 我們需要在外部瀏覽器中打開(kāi)百度界面, 并直接搜索某一段字符串, 我們可以通過(guò)下面的代碼來(lái)完成這個(gè)需求
- 效果圖:
- 輸入框中輸入內(nèi)容后, 通過(guò)點(diǎn)擊View直接跳轉(zhuǎn)Safari, 然后使用百度直接搜索指定字符串
#import "ViewController.h"
@interface ViewController ()
/** 輸入框 */
@property (nonatomic, strong) UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 200, 40)];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.textField];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 沒(méi)有內(nèi)容直接返回
if (self.textField.text.length == 0) return;
// 需要搜索的內(nèi)容
NSString * keyword = self.textField.text;
//適配 iOS9 字符串UTF8編碼
if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_9_0) {
keyword = [keyword stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}else {
keyword = [keyword stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
// 拼接鏈接字符傳
NSString * urlStart = @"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=";
NSString * urlEnd = @"&rsv_pq=80c7023000194588&rsv_t=e923%2BJi6SI0Q7Kl1q1%2BUl%2Bq7jbwN0GzkIghhykTbOJO0WX2%2BnR6iKTwQWLI&rsv_enter=1&inputT=7275&rsv_sug3=20&rsv_sug1=19&rsv_sug2=0&rsv_sug4=7642";
NSMutableString * urlStr = [[NSMutableString alloc]init];
[urlStr appendString:urlStart];
[urlStr appendString:keyword];
[urlStr appendString:urlEnd];
NSURL * url = [NSURL URLWithString:[NSString stringWithString:urlStr]];
//適配 iOS10 跳轉(zhuǎn)Safari瀏覽器
if ([[UIApplication sharedApplication] canOpenURL:url]) {
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_x_Max) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}else {
[[UIApplication sharedApplication] openURL:url];
}
}
}
@end