swift 基础网络请求+解析数据用第三方Alamfire

版权声明:iOS技术小牛 https://blog.csdn.net/weixin_42925415/article/details/84141879
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 )

猜你喜欢

转载自blog.csdn.net/weixin_42925415/article/details/84141879