1.使用www.showapi.com上的接口,需要注册添加一个App,这样才能获取appid和secret密钥,调用前需要订购套餐(选免费的就可以了);
2.外部库Podfile文件内容,SnapKit这里暂时不需要用到:
platform :ios,'8.0'
use_frameworks!
target 'WxArticle' do
pod 'Alamofire','~> 3.0'
pod 'SwiftyJSON',:git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
pod 'SnapKit','~> 0.17.0'
end
3.桥接头文件参考:http://www.jb51.cc/article/p-pcleyxep-te.html
4.App Transport Security has blocked a cleartext HTTP (http://www.jb51.cc/tag/http://) resource load since it is insecure.参考:http://www.jb51.cc/article/p-acbjaooh-tg.html
5.请求url编码,request.swift
//
// request.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//
import Foundation
class Request {
var appId: Int
var timestamp: String {
return NSDate.currentDate("yyyyMMddHHmmss")
}
var signMethod = "md5"
var resGzip = 0
var allParams = [(String,String)]()
init(appId: Int) {
self.appId = appId
}
func sign(appParams: [(String,String)],secret: String) -> String {
self.allParams = appParams
self.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.lowercaseString
return 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 = 1
init(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 SwiftyJSON
class Response {
var showapi_res_code = -1
var showapi_res_error = ""
}
struct CategoryChildItem {
var id = 0
var 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 ?? -1
super.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 = name
for 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 = -1
var name = ""
var num = -1
var trend = ""
}
class HotWordResponse: Response {
var list = [HotWordInfo]()
func setData(data: AnyObject) {
let json = JSON(data)
super.showapi_res_code = json["showapi_res_code"].int ?? -1
super.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") ?? -1
hotWordInfo.name = name
hotWordInfo.num = Int(item["num"].string ?? "-1") ?? -1
hotWordInfo.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 Foundation
class 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.
//
@H_301_411@#ifndef QueryPhoneNumber_Objective_CBridgingHeader_h
@H_301_411@#define QueryPhoneNumber_Objective_CBridgingHeader_h
@H_301_411@#import <CommonCrypto/CommonHMAC.h>
@H_301_411@#endif
9.扩展String,计算md5,扩展日期格式化,extension.swift
//
// extension.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//
import Foundation
extension 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 = dateFormat
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter.stringFromDate(NSDate())
}
}
10.ViewController.swift
//
// ViewController@H_301_411@.swift
// HotSearch
//
// Created by tutujiaw on 16/3/25.
// Copyright © 2016年 tujiaw. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UITableViewController {
override func viewDidLoad() {
super@H_301_411@.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
self@H_301_411@.navigationItem@H_301_411@.title = "热搜分类"
let request = HotWordCategoryRequest()
Alamofire@H_301_411@.request(@H_301_411@.GET,request@H_301_411@.url())@H_301_411@.responseJSON { (response) -> Void in
if response@H_301_411@.result@H_301_411@.isSuccess {
if let value = response@H_301_411@.result@H_301_411@.value {
Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.setData(value)
self@H_301_411@.tableView@H_301_411@.reloadData()
}
}
}
}
override func didReceiveMemoryWarning() {
super@H_301_411@.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
if section < Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count {
let item = Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[section]
print("child list count:\(item.childList.count)")
//
return Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[section]@H_301_411@.childList@H_301_411@.count
}
return 0
}
override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CELL_ID = "HOT_WORD_CATEGORY_CELL_ID"
let cell = tableView@H_301_411@.dequeueReusableCellWithIdentifier(CELL_ID,forIndexPath: indexPath)
if indexPath@H_301_411@.section < Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count {
var item = Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[indexPath@H_301_411@.section]
if indexPath@H_301_411@.row < item@H_301_411@.childList@H_301_411@.count {
cell@H_301_411@.textLabel?@H_301_411@.text = item@H_301_411@.childList[indexPath@H_301_411@.row]@H_301_411@.name
}
}
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count
}
override func tableView(tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
if section < Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count {
return Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[section]@H_301_411@.name
}
return ""
}
override func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("index:\(indexPath.row)")
if indexPath@H_301_411@.section < Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count {
let item = Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[indexPath@H_301_411@.section]
if indexPath@H_301_411@.row < item@H_301_411@.childList@H_301_411@.count {
print("\(item.childList[indexPath.row].name),\(item.childList[indexPath.row].id)")
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {
if segue@H_301_411@.identifier == "HOT_WORD_SEGUE" {
let target = segue@H_301_411@.destinationViewController as? HotWordTableViewController
let indexPath = tableView@H_301_411@.indexPathForSelectedRow
if indexPath?@H_301_411@.section < Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list@H_301_411@.count {
let item = Data@H_301_411@.sharedManage@H_301_411@.hotWordCategory@H_301_411@.list[(indexPath?@H_301_411@.section)!]
if indexPath?@H_301_411@.row < item@H_301_411@.childList@H_301_411@.count {
target?@H_301_411@.name = item@H_301_411@.childList[(indexPath?@H_301_411@.row)!]@H_301_411@.name
target?@H_301_411@.typeId = item@H_301_411@.childList[(indexPath?@H_301_411@.row)!]@H_301_411@.id
}
}
}
}
}
11.HotWordTableViewController.swift
//
// HotWordTableViewController@H_301_411@.swift
// HotSearch
//
// Created by tutujiaw on 16/3/26.
// Copyright © 2016年 tujiaw. All rights reserved.
//
import UIKit
import Alamofire
class HotWordTableViewController: UITableViewController {
var name = ""
var typeId = 0
override func viewDidLoad() {
super@H_301_411@.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
self@H_301_411@.navigationItem@H_301_411@.title = name
let request = HotWordRequest(typeId: self@H_301_411@.typeId)
Alamofire@H_301_411@.request(@H_301_411@.GET,request@H_301_411@.url())@H_301_411@.responseJSON { (response) -> Void in
if response@H_301_411@.result@H_301_411@.isSuccess {
if let value = response@H_301_411@.result@H_301_411@.value {
Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.clear()
Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.setData(value)
self@H_301_411@.tableView@H_301_411@.reloadData()
}
}
}
}
override func didReceiveMemoryWarning() {
super@H_301_411@.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.list@H_301_411@.count
}
override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CELL_ID = "HOT_WORD_CELL_ID"
let cell = tableView@H_301_411@.dequeueReusableCellWithIdentifier(CELL_ID,forIndexPath: indexPath)
if indexPath@H_301_411@.row < Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.list@H_301_411@.count {
let item = Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.list[indexPath@H_301_411@.row]
cell@H_301_411@.textLabel?@H_301_411@.text = item@H_301_411@.name
}
return cell
}
override func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath@H_301_411@.row < Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.list@H_301_411@.count {
let keyword = Data@H_301_411@.sharedManage@H_301_411@.hotWord@H_301_411@.list[indexPath@H_301_411@.row]@H_301_411@.name
if let newKeyword = keyword@H_301_411@.stringByAddingPercentEncodingWithAllowedCharacters(@H_301_411@.URLHostAllowedCharacterSet()) {
if let url = NSURL(string: "https://www.baidu.com/s?wd=\(newKeyword)") {
UIApplication@H_301_411@.sharedApplication()@H_301_411@.openURL(url)
}
}
}
}
}
github地址:https://github.com/tujiaw/HotSearch
截图: