8.2 UiTableView与http关联 (音乐网络播放器)

8.2 UiTableView与http关联

(音乐网络播放器)

新建一个文件,名为ChannelModel

import Foundation

class ChannelModel {

    var channel_id: String!

    var channel_name: String!

    var coverUrl: NSURL!

    

    init(dict: NSDictionary) {

        if let chId = dict["channel_id"] {

            channel_id = chId as! String

        }

        

        if let chName = dict["channel_name"] {

            channel_name = chName as! String

        }

        

        if let cUrl = dict["coverUrl"] {

            coverUrl = NSURL(string: cUrl as! String)

        }

    }

    

    init() {

        

    }
}

回到viewcontrol文件中

开始写代码

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var tableView: UITableView!                //创建一个tableView
    var models: Array?           //创建一个数组models

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: self.view.bounds, style: .Plain) //定义tableView铺满全屏
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
        
        let url = NSURL(string: "https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json")
        if let u = url {
            let task = NSURLSession.sharedSession().dataTaskWithURL(u, completionHandler: { (data, response, error) in
                if error == nil {
                    if let httpResponse = response as? NSHTTPURLResponse {
                        if httpResponse.statusCode == 200 {
                            if let d = data {
                                let channels = try!NSJSONSerialization.JSONObjectWithData(d, options: .AllowFragments) as?Array
                                self.models = channels?.map({(e: NSDictionary) ->ChannelModel in
                                    return ChannelModel(dict: e)
                                })
                               self.performSelectorOnMainThread(#selector(self.refreshTableView),
                                    withObject:nil, waitUntilDone: true)       //在主线程中显示内容
                                print(NSThread.isMainThread())
                            }
                        }
                    }
                }
                
            })
            task.resume()                   //显示task(连接后的内容)
        }

    }

    

    func refreshTableView() {
        print("Thread", NSThread.isMainThread())
        
        tableView.reloadData()                  //重载页面
}
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    guard let m = models else{
        return 0
    }
    return m .count
}

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }                                       //往cell行里面填内容,保证不为空
        
        let model = models![indexPath.row]
        cell?.textLabel?.text = model.channel_name
        return cell!                            //定义cell内容为频道的名字
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
        let model = models![indexPath.row]
        print(model.channel_name, model.channel_id)   //打印频道名,和频道id
    }
}

你可能感兴趣的:(8.2 UiTableView与http关联 (音乐网络播放器))