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.
//
#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 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.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.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 in
if 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? HotWordTableViewController
let indexPath = tableView.indexPathForSelectedRow
if 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)!].name
target?.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 Alamofire
class HotWordTableViewController: UITableViewController {
var name = ""
var typeId = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
self.navigationItem.title = name
let request = HotWordRequest(typeId: self.typeId)
Alamofire.request(.GET,request.url()).responseJSON { (response) -> Void in
if 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].name
if 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
截图: