点击下载Alamofire-Swift解析网络数据 , 密码 : 4ymo
下载文件后解压
把解压文件直接拖拽到项目的文件夹内 (桌面的文件夹内 而不是Xcode内)
然后在Xcode文件夹双指辅助点按 ,选择Add files to “项目名称”
添加 Alamofile.xcodeproj
以下为ViewController.swift
链接:https://pan.baidu.com/s/1U6GTR9_yof2WV26GyxjIww 密码:4ymo
import UIKit
import Alamofire
//相当于Object,Model
class MyModel: NSObject {
var idNumber = Int()
var nameString = String()
}
//代理
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
//全局
var table = UITableView()
//数据源
var DataSoure = NSMutableArray()
var data = NSDictionary()
var categories = NSDictionary()
var Optional = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
//table
table = UITableView(frame: UIScreen.main.bounds, style: .plain)
table.delegate = self
table.dataSource = self
self.view.addSubview(table)
// Do any additional setup after loading the view, typically from a nib.
//解析 请求网络数据
Alamofire.request("http://live.ximalaya.com/live-web/v4/homepage?device=iPhone", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON{(respionse) in
if (respionse.error == nil){
print("请求成功")
self.data = respionse.result.value as! NSDictionary
self.categories = self.data.object(forKey: "data") as! NSDictionary
self.Optional = self.categories.object(forKey: "categories") as! NSArray
for atm in self.Optional{
let irs = atm as! NSDictionary
let mymodel = MyModel()
mymodel.idNumber = irs["id"] as! Int
mymodel.nameString = irs["name"] as! String
self.DataSoure .add(mymodel)
}
self.table.reloadData()
}else{
print("请求失败")
}
}
}
//表格多少行 方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataSoure.count
}
//cell方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView .dequeueReusableCell(withIdentifier: "cell")
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
// 主标题
cell?.textLabel?.text = (DataSoure[indexPath.row] as! MyModel).nameString
//副标题 强转String
cell?.detailTextLabel?.text = String((DataSoure[indexPath.row] as! MyModel).idNumber)
return cell!
}
}