【实例补充】Swift之HandyJSON->Model
2017-02-28 本文已影响274人
布袋的世界
原理:HandyJSON的作者 :http://www.jianshu.com/p/cbed87d8656d
参考:Github.com 上的 喜玛拉雅
HandyJSON实例练手
首页Pod 引入三个库
HandyJSON # 解析MODEL
SwiftyJSON # 解析网络数据的jsonstring
Alamofire # 解析网络数据(封装)
//
// ApiModel.swift
// AppHandyJSONDemo
//
// Created by apiapia on 2/27/17.
// Copyright © 2017 apiapia. All rights reserved.
// http://mobile.ximalaya.com/mobile/discovery/v4/recommends?channel=ios-b1&device=iPhone&includeActivity=true&includeSpecial=true&scale=2&version=5.4.21
import UIKit
fileprivate let XmlyRecommendURL = "http://mobile.ximalaya.com/mobile/discovery/v4/recommends?channel=ios-b1&device=iPhone&includeActivity=true&includeSpecial=true&scale=2&version=5.4.21"
class APIModel:NSObject {
class func requestXmlyAPI(_ finished:@escaping (_ result: AnyObject?, _ error: NSError?) -> ()) {
XMNetworkTool.shareInstance.xm_requestData(methodType: .POST, urlString: XmlyRecommendURL, parameters: nil) { (result, error) in
finished(result, error)
}
}
//
// XMNetworkTool.swift
// XMXMLYFM
//
import UIKit
import Alamofire
enum XMRequestType: Int {
case GET
case POST
}
class XMNetworkTool: NSObject {
static let shareInstance : XMNetworkTool = {
let tools = XMNetworkTool()
return tools
}()
}
extension XMNetworkTool {
func xm_requestData(methodType:XMRequestType,urlString : String, parameters:[String : AnyObject]?,finished:@escaping(_ result: AnyObject?,_ error:NSError?) ->()){
let resultCallBack = {(response: DataResponse<Any>) in
if response.result.isSuccess {
finished(response.result.value as AnyObject?,nil)
}else{
finished(nil, response.result.error as NSError?)
}
}
// 2.请求数据
let httpMethod: HTTPMethod = methodType == .GET ? .get : .post
request(urlString, method: httpMethod, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: resultCallBack)
}
}
//
// XmlyModel.swift
// AppHandyJSONDemo
//
// Created by apiapia on 2/27/17.
// Copyright © 2017 apiapia. All rights reserved.
//
import HandyJSON
import UIKit
//小编推荐
class XmlyModel:HandyJSON {
var editorRecommendAlbums:[AlbumsModel]?
var focusImages:FocusImagesModel?
required init() {}
}
class AlbumsModel:HandyJSON {
var ret = 0
var title:String?
var hasMore:Bool?
var list:[AlbumsListModel]?
required init() {}
}
class AlbumsListModel:HandyJSON {
var id:Int?
var albumId:Int?
var nickname:String?
var coverMiddle:String?
var playsCounts:Int?
required init() {}
}
//精品听单
class SpecialColumnListModel:HandyJSON{
var specialId:Int?
var title:String?
var coverPath:String?
required init() {}
}
//
// XMLYViewController.swift
// AppHandyJSONDemo
//
// Created by apiapia on 2/27/17.
// Copyright © 2017 apiapia. All rights reserved.
//
import UIKit
import HandyJSON
import SwiftyJSON
import SVProgressHUD
class XMLYViewController: UIViewController {
var tableView:UITableView!
var albumsModel:AlbumsModel!
var albumsList:[AlbumsListModel] = [] {
didSet{
self.tableView.reloadData()
}
}
var imageList:[FocusImageListModel] = []
var xmlyModel:XmlyModel!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
func setupUI(){
tableView = UITableView(frame:CGRect(x: 0, y: 0, width: AppScreenWidth, height: AppScreenHeight) , style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(tableView)
loadData()
}
func loadData(){
/*
[SVProgressHUD show];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// time-consuming task
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
});
*/
//SVProgressHUD.setMinimumDismissTimeInterval(1.0)
SVProgressHUD.show(withStatus: "正在加载")
//SVProgressHUD.setDefaultMaskType(.black)
// 请求网络数据
APIModel.requestXmlyAPI { (result, error) in
// print(result)
if error != nil {
// 注意是 showError
SVProgressHUD.showError(withStatus: "登陆失败,请检查网络")
return
}
guard let dict = result?["editorRecommendAlbums"] as? NSDictionary else {
return
}
//写法1
// SVProgressHUD.showSuccess(withStatus: "加载成功")
SVProgressHUD.dismiss()
self.albumsModel = JSONDeserializer<AlbumsModel>.deserializeFrom(dict: dict)
self.albumsList = self.albumsModel.list!
print (self.albumsList)
// self.tableView.reloadData() 有didSet了,这句注释
//直接取二级节点
//focusImages.list 直接取 .deserializeFrom(json:JSON(result!).description , designatedPath:"focusImages.title")
self.xmlyModel = JSONDeserializer<XmlyModel>.deserializeFrom(json: JSON(result!).description)
/*
var focusImages : NSArray? {
didSet{
guard let specialList = focusImages else { return }
for index in 0..<specialList.count {
let image:FocusImagesList = specialList[index] as! FocusImagesList
imageArray.append(image.pic!)
}
self.cycleScrollView.imageUrls = self.imageArray
}
}
self.headerView.focusImages = self.recommends.focusImages?.list as NSArray?
*/
self.imageList = (self.xmlyModel.focusImages?.list)!
for i in 0..<(self.imageList.count) {
print ("\(self.imageList[i].pic!)")
}
}
}
}
extension XMLYViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albumsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "\(self.albumsList[indexPath.row].nickname!)"
return cell
}
}
总结:共用了HandyJSON的三个用法,分别是
->###
1、SwiftJSON+HandyJSON解析为String .deserializeFrom(json:JSON(result!).description
2、HandyJSON解析为dictionary JSONDeserializer<AlbumsModel>.deserializeFrom(dict: dict)
3、HandyJSON的Array 用法 self.doubanList = (JSONDeserializer<DouBanListModel>
.deserializeModelArrayFrom(json: JSON(arr!).description) as! [DouBanListModel]?)!
->###
//
// DouBanListModel.swift
// AppHandyJSONDemo
//
// Created by apiapia on 2/27/17.
// Copyright © 2017 apiapia. All rights reserved.
// fileprivate let DouBanListAPI = "https://www.douban.com/j/app/radio/channels"
import UIKit
import HandyJSON
class DouBanListModel:HandyJSON {
var name_en:String?
var seq_id:Int?
var abbr_en:String?
var name:String?
var channel_id = 0
required init(){}
}