Swift 使用Alamofire 不用pods 解析網路資料
阿新 • • 發佈:2018-12-17
點選下載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! } }