8.2 UiTableView與http關(guān)聯(lián)
(音樂網(wǎng)絡(luò)播放器)
新建一個(gè)文件凳干,名為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! //創(chuàng)建一個(gè)tableView
var models: Array<ChannelModel>? //創(chuàng)建一個(gè)數(shù)組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) //在主線程中顯示內(nèi)容
print(NSThread.isMainThread())
}
}
}
}
})
task.resume() //顯示task(連接后的內(nèi)容)
}
}
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行里面填內(nèi)容,保證不為空
let model = models![indexPath.row]
cell?.textLabel?.text = model.channel_name
return cell! //定義cell內(nèi)容為頻道的名字
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
let model = models![indexPath.row]
print(model.channel_name, model.channel_id) //打印頻道名,和頻道id
}
}