swift 网络搜索热词排行

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
截图:

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...