本文主要是介绍swift 网络搜索热词排行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.使用www.showapi.com上的接口,需要注册添加一个App,这样才能获取appid和secret密钥,调用前需要订购套餐(选免费的就可以了);
2.外部库Podfile文件内容,SnapKit这里暂时不需要用到:
platform :ios, '8.0'
use_frameworks!target 'WxArticle' dopod 'Alamofire', '~> 3.0'pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'pod 'SnapKit', '~> 0.17.0'
end
3.桥接头文件参考:http://blog.csdn.net/tujiaw/article/details/47048343
4.App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure.参考:http://blog.csdn.net/tujiaw/article/details/49975761
5.请求url编码,request.swift
//
// request.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//import Foundationclass Request {var appId: Intvar timestamp: String {return NSDate.currentDate("yyyyMMddHHmmss")}var signMethod = "md5"var resGzip = 0var allParams = [(String, String)]()init(appId: Int) {self.appId = appId}func sign(appParams: [(String, String)], secret: String) -> String {self.allParams = appParamsself.allParams.append(("showapi_appid", String(self.appId)))self.allParams.append(("showapi_timestamp", self.timestamp))let sortedParams = allParams.sort{$0.0 < $1.0}var str = ""for item in sortedParams {str += (item.0 + item.1)}str += secret.lowercaseStringreturn str.md5()}func url(mainUrl: String, sign: String) -> String {var url = mainUrl + "?"for param in self.allParams {url += "\(param.0)=\(param.1)&"}url += "showapi_sign=\(sign)"return url}
}class HotWordCategoryRequest: Request {init () {super.init(appId: 17262)}func url() -> String {let sign = self.sign([(String, String)](), secret: "21b693f98bd64e71a9bdbb5f7c76659c")return super.url("http://route.showapi.com/313-1", sign: sign)}
}class HotWordRequest: Request {var typeId = 1init(typeId: Int) {super.init(appId: 17262)self.typeId = typeId}func url() -> String {let sign = self.sign([("typeId", "\(self.typeId)")], secret: "21b693f98bd64e71a9bdbb5f7c76659c")return super.url("http://route.showapi.com/313-2", sign: sign)}
}
6.应答json解码,response.swift
//
// response.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//import Foundation
import SwiftyJSONclass Response {var showapi_res_code = -1var showapi_res_error = ""
}struct CategoryChildItem {var id = 0var name = ""
}struct CategoryItem {var name = ""var childList = [CategoryChildItem]()
}class HotWordCategoryResponse: Response {var list = [CategoryItem]()func setData(data: AnyObject) {let json = JSON(data)super.showapi_res_code = json["showapi_res_code"].int ?? -1super.showapi_res_error = json["showapi_res_error"].string ?? ""if let list = json["showapi_res_body"]["list"].array {for item in list {var categoryItem = CategoryItem()guard let name = item["name"].string,let childList = item["childList"].array else {continue}categoryItem.name = namefor child in childList {guard let id = child["id"].string,let name = child["name"].string else {continue}categoryItem.childList.append(CategoryChildItem(id: Int(id)!, name: name))}self.list.append(categoryItem)}}}
}struct HotWordInfo {var level = -1var name = ""var num = -1var trend = ""
}class HotWordResponse: Response {var list = [HotWordInfo]()func setData(data: AnyObject) {let json = JSON(data)super.showapi_res_code = json["showapi_res_code"].int ?? -1super.showapi_res_error = json["showapi_res_error"].string ?? ""if let list = json["showapi_res_body"]["list"].array {for item in list {guard let name = item["name"].string else {continue}var hotWordInfo = HotWordInfo()hotWordInfo.level = Int(item["level"].string ?? "-1") ?? -1hotWordInfo.name = namehotWordInfo.num = Int(item["num"].string ?? "-1") ?? -1hotWordInfo.trend = item["trend"].string ?? ""self.list.append(hotWordInfo)}}}func clear() {self.list.removeAll()}
}
7.数据管理,缓存,dataManage.swift
//
// dataManage.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//import Foundationclass Data {static let sharedManage = Data()var hotWordCategory = HotWordCategoryResponse()var hotWord = HotWordResponse()
}
8.Objective-CBridgingHeader.h
//
// Objective-CBridgingHeader.h
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//#ifndef QueryPhoneNumber_Objective_CBridgingHeader_h#define QueryPhoneNumber_Objective_CBridgingHeader_h#import <CommonCrypto/CommonHMAC.h>#endif
9.扩展String,计算md5,扩展日期格式化,extension.swift
//
// extension.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//import Foundationextension String {func md5() -> String! {let str = self.cStringUsingEncoding(NSUTF8StringEncoding)let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))let digestLen = Int(CC_MD5_DIGEST_LENGTH)let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)CC_MD5(str!, strLen, result)let hash = NSMutableString()for i in 0..<digestLen {hash.appendFormat("%02x", result[i])}result.destroy()return String(format: hash as String)}
}extension NSDate {static func currentDate(dateFormat: String) -> String {let dateFormatter = NSDateFormatter()dateFormatter.dateFormat = dateFormatdateFormatter.locale = NSLocale.currentLocale()return dateFormatter.stringFromDate(NSDate())}
}
10.ViewController.swift
//
// ViewController.swift
// HotSearch
//
// Created by tutujiaw on 16/3/25.
// Copyright © 2016年 tujiaw. All rights reserved.
//import UIKit
import Alamofireclass ViewController: UITableViewController {override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.self.navigationItem.title = "热搜分类"let request = HotWordCategoryRequest()Alamofire.request(.GET, request.url()).responseJSON { (response) -> Void inif response.result.isSuccess {if let value = response.result.value {Data.sharedManage.hotWordCategory.setData(value)self.tableView.reloadData()}}}}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {if section < Data.sharedManage.hotWordCategory.list.count {let item = Data.sharedManage.hotWordCategory.list[section]print("child list count:\(item.childList.count)")//return Data.sharedManage.hotWordCategory.list[section].childList.count}return 0}override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {let CELL_ID = "HOT_WORD_CATEGORY_CELL_ID"let cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID, forIndexPath: indexPath)if indexPath.section < Data.sharedManage.hotWordCategory.list.count {var item = Data.sharedManage.hotWordCategory.list[indexPath.section]if indexPath.row < item.childList.count {cell.textLabel?.text = item.childList[indexPath.row].name}}return cell}override func numberOfSectionsInTableView(tableView: UITableView) -> Int {return Data.sharedManage.hotWordCategory.list.count}override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {if section < Data.sharedManage.hotWordCategory.list.count {return Data.sharedManage.hotWordCategory.list[section].name}return ""}override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {print("index:\(indexPath.row)")if indexPath.section < Data.sharedManage.hotWordCategory.list.count {let item = Data.sharedManage.hotWordCategory.list[indexPath.section]if indexPath.row < item.childList.count {print("\(item.childList[indexPath.row].name), \(item.childList[indexPath.row].id)")}}}override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {if segue.identifier == "HOT_WORD_SEGUE" {let target = segue.destinationViewController as? HotWordTableViewControllerlet indexPath = tableView.indexPathForSelectedRowif indexPath?.section < Data.sharedManage.hotWordCategory.list.count {let item = Data.sharedManage.hotWordCategory.list[(indexPath?.section)!]if indexPath?.row < item.childList.count {target?.name = item.childList[(indexPath?.row)!].nametarget?.typeId = item.childList[(indexPath?.row)!].id}}}}}
11.HotWordTableViewController.swift
//
// HotWordTableViewController.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//import UIKit
import Alamofireclass HotWordTableViewController: UITableViewController {var name = ""var typeId = 0override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.self.navigationItem.title = namelet request = HotWordRequest(typeId: self.typeId)Alamofire.request(.GET, request.url()).responseJSON { (response) -> Void inif response.result.isSuccess {if let value = response.result.value {Data.sharedManage.hotWord.clear()Data.sharedManage.hotWord.setData(value)self.tableView.reloadData()}}}}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return Data.sharedManage.hotWord.list.count}override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {let CELL_ID = "HOT_WORD_CELL_ID"let cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID, forIndexPath: indexPath)if indexPath.row < Data.sharedManage.hotWord.list.count {let item = Data.sharedManage.hotWord.list[indexPath.row]cell.textLabel?.text = item.name}return cell}override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {if indexPath.row < Data.sharedManage.hotWord.list.count {let keyword = Data.sharedManage.hotWord.list[indexPath.row].nameif let newKeyword = keyword.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) {if let url = NSURL(string: "https://www.baidu.com/s?wd=\(newKeyword)") {UIApplication.sharedApplication().openURL(url)}}}}
}
点击热搜词可以直接打开浏览器在百度里面进行搜索。
github地址:https://github.com/tujiaw/HotSearch
截图:
这篇关于swift 网络搜索热词排行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!