tableView中URL下载

ViewController

var tableView: UITableView!
    var models: Array?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: self.view.bounds, style: .Plain)
        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
                                
                                //1. 在闭包中使用成员变量
                                //2. NSArray不能使用map
                                self.models = channels?.map({ (e: NSDictionary) -> ChannelModel in
                                    return ChannelModel(dict: e)
                                })
                                
//                                tableView.performSelectorOnMainThread(#selector(table.self.reloadData()), withObject: nil, waitUntilDone: false)
                                //在refreshTableView放入主线程中执行
                                self.performSelectorOnMainThread(#selector(self.refreshTableView), withObject: nil, waitUntilDone: true)
                                
                                
                                
                                //更新界面必须在主线程
                                print(NSThread.isMainThread())
                            }
                        }
                    }
                }
            })
            task.resume()
        }
    }
    
    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")
        }
        
        let model = models![indexPath.row]
        cell?.textLabel?.text = model.channel_name
        return cell!
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let model = models![indexPath.row]
        print(model.channel_name, model.channel_id)
    }

ChannelModel

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() {
        
    }
}

你可能感兴趣的:(tableView中URL下载)