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<ChannelModel>?           //创建一个数组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<NSDictionary>
                                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
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,110评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,271评论 4 61
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,156评论 19 139
  • 两年学生会的重复工作,在大二期末的时候我终于选择了放手。 两年前的自己,离开家乡来到1200公里外的陌生城...
    劉SHI琪阅读 602评论 0 0
  • 假期比上班还累,是因为期待着放松,却没有真正轻松。比如昨天。登高踏青祭祖,聊天聚会吃饭,练车远行发飙,没管孩子,没...
    安曼阅读 406评论 0 0