swift 网络搜索热词排行

swift 网络搜索热词排行,第1张

概述1.使用www.showapi.com上的接口,需要注册添加一个App,这样才能获取appid和secret密钥,调用前需要订购套餐(选免费的就可以了); 2.外部库Podfile文件内容,SnapKit这里暂时不需要用到: platform :ios, '8.0'use_frameworks!target 'WxArticle' do pod 'Alamofire', '~> 3.0'

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 Foundationclass 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 Foundationimport SwiftyJsONclass 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 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 = 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 UIKitimport 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 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 UIKitimport Alamofireclass 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
截图:

总结

以上是内存溢出为你收集整理的swift 网络搜索热词排行全部内容,希望文章能够帮你解决swift 网络搜索热词排行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1078155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存