swift 基礎網路請求+解析資料用第三方Alamfire
阿新 • • 發佈:2018-12-17
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var dic:NSDictionary? var dic1:NSArray = [] var table:UITableView? var dict:NSDictionary = [:] var dictr:NSDictionary = [:] func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dic1.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") let name:NSDictionary = dic1[indexPath.row] as! NSDictionary if cell==nil { cell=UITableViewCell(style:.default, reuseIdentifier: "cell") } cell?.textLabel?.text=name["name"] as? String return cell! } override func viewDidLoad() { super.viewDidLoad() Alamofire.request("http://live.ximalaya.com/live-web/v4/homepage?device=iPhone", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in if(response.error == nil){ print("請求成功") print(response.result.value as Any) self.dic = response.result.value as? NSDictionary self.dictr = self.dic?.object(forKey: "data") as! NSDictionary self.dic1 = (self.dictr.object(forKey: "categories") as! NSArray) print(self.dic1 as Any) }else{ print("請求失敗\(String(describing: response.error))") } //解析網址 self.table?.reloadData() } self.table = UITableView(frame: self.view.frame, style: .plain) self.table?.delegate=self self.table?.dataSource=self self.view.addSubview(self.table!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //最後提一句,基礎swiift解析網路圖片的方法 //url(string:後面加網址) let urlstr=NSURL(string: (name["coverLarge"] as! String)) let data = NSData(contentsOf: urlstr! as URL) cell.imgv.image=UIImage(data: data! as Data )