需求说明
1、原来默认的搜索引擎为百度,现在添加切换搜索引擎的功能。
2、第一阶段提供固定的8个搜索引擎提供切换。
3、切换后,当搜索关键词不是链接则使用(搜索引擎+关键词)进行搜索
相关代码
SearchEngineTool是个单例,管理拥有哪些引擎以及当前是哪个搜索引擎。
初始化搜索引擎
var allSearchEngines: [SearchEngineModel] {
get {
var engineArr: [SearchEngineModel]
if let cacheEngine = self.cache?.object(forKey: "searchEngineCacheKey") as? [SearchEngineModel],cacheEngine.count <= defaultSearchEngines.count {
engineArr = cacheEngine
} else {
var tempArr = [SearchEngineModel]()
for engineDict in self.defaultSearchEngines {
let engine = SearchEngineModel(engineDict)
tempArr.append(engine)
}
engineArr = tempArr
self.allSearchEngines = engineArr
}
return engineArr
}
set {
self.cache?.setObject(newValue as NSCoding, forKey: "searchEngineCacheKey")
}
}
获取当前搜索引擎
var selectEngine: SearchEngineModel {
get {
return allSearchEngines.filter { (engine) -> Bool in
return engine.isSelectEngine
}.first ?? allSearchEngines.first!
}
}
切换搜索引擎的方法
func changeSelectEngine(_ index: Int) {
selectEngine.isSelectEngine = false
allSearchEngines[index].isSelectEngine = true
self.cache?.setObject(allSearchEngines as NSCoding, forKey: "searchEngineCacheKey")
}
- 搜索时使用
var searchEngineURL: String {
get {
return searchEngineTool.selectEngine.engineUrl ?? "http://m.baidu.com/s?from=1006749l&word="
}
}
fileprivate func loadAndAddToHistoryWithURLString(_ URLString: String) {
guard !isSearchUrlToChangeSearchKey(URLString) else { return }
var text = self.searchEngineURL + URLString
if let _ = MainViewFacade.sharedInstance.mainViewModel.verificationURL(URLString)
{
text = URLString
}
if UserDefaults.standard.bool(forKey: "isOpenSearch")
{
self.addKeyworkToSearchHistory(URLString)
}
if let request = MainViewFacade.sharedInstance.mainViewModel.verificationURL(text) {
urlBarView?.clearText(UITapGestureRecognizer())
urlBarView?.cancel()
// MainViewFacade.sharedInstance.currentPageView().loadRequest(request)
mainViewController()?.pageViewManager.newTabLoadRequest(request)
if let absoluteString = request.url?.absoluteString {
urlBarView?.addressTextString = absoluteString
}
cancelFocus()
}
}
URLString:将要打开的链接或者关键词
如果MainViewFacade.sharedInstance.mainViewModel.verificationURL(URLString)返回有值说明URLString是正常url则直接打开该url。
否则(self.searchEngineURL + URLString)添加搜索引擎前缀。
注:http://m.baidu.com/s?from=1006749l&word=中的 1006749l 是公司该APP的tn字段,能提供收入,不能随便修改。
网友评论