首頁(yè)
課程目標(biāo)
- 網(wǎng)絡(luò) JSON 轉(zhuǎn)模型
- 自定義 Cell
接口定義
文檔地址
http://open.weibo.com/wiki/2/statuses/home_timeline
接口地址
https://api.weibo.com/2/statuses/home_timeline.json
HTTP 請(qǐng)求方式
- GET
請(qǐng)求參數(shù)
參數(shù) | 描述 |
---|---|
access_token | 采用OAuth授權(quán)方式為必填參數(shù)愉棱,其他授權(quán)方式不需要此參數(shù)唆铐,OAuth授權(quán)后獲得 |
since_id | 若指定此參數(shù),則返回ID比since_id大的微博(即比since_id時(shí)間晚的微博)奔滑,默認(rèn)為0 |
max_id | 若指定此參數(shù)艾岂,則返回ID小于或等于max_id的微博,默認(rèn)為0 |
測(cè)試 URL:https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00ml8IrFLUkOXB32bb2d4ddd0u2gmj
微博數(shù)據(jù)模型
加載微博數(shù)據(jù)
- 在
HMHomeTableViewController
中添加加載微博數(shù)據(jù)方法
/// 加載微博數(shù)據(jù)的方法
private func loadData() {
// 定義 url 與參數(shù)
let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
let params = [
"access_token": HMUserAccountViewModel.sharedUserAccount.accessToken!
]
HMNetworkTools.shareTools.request(.GET, url: urlString, params: params) { (result, error) -> () in
if error != nil {
print("加載失敗\(error)")
return
}
print(result)
}
}
- 執(zhí)行方法加載微博數(shù)據(jù)
override func viewDidLoad() {
super.viewDidLoad()
if !UserAccountViewModel.sharedUserAccount.userLogon {
visitorView?.setupInfo(nil, message: "關(guān)注一些人朋其,回這里看看有什么驚喜")
return
}
loadData()
}
運(yùn)行測(cè)試
定義微博模型
- 定義微博模型
/// 微博模型
class HMStatus: NSObject {
// MARK: - 模型屬性
/// 創(chuàng)建時(shí)間
var created_at: String?
/// 微博ID
var id: Int = 0
/// 微博信息內(nèi)容
var text: String?
/// 微博來(lái)源
var source: String?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
}
- 將返回?cái)?shù)據(jù)字典轉(zhuǎn)模型
HMNetworkTools.shareTools.request(.GET, url: urlString, params: params) { (result, error) -> () in
...
// 加載成功
guard let statusesDict = result?["statuses"] as? [[String: AnyObject]] else {
return
}
// 字典轉(zhuǎn)模型
// 定義臨時(shí)數(shù)據(jù)
var tempArray = [HMStatus]()
for statusDict in statusesDict {
let status = HMStatus(dict: statusDict)
tempArray.append(status)
}
}
- 定義微博列表視圖模型
HMStatusListViewModel
/// 微博數(shù)組視圖模型
class HMStatusListViewModel: NSObject {
// 微博數(shù)組
var statuses: [HMStatus]?
}
- 將加載數(shù)據(jù)的方法移動(dòng)至
HMStatusListViewModel
/// 加載微博數(shù)據(jù)的方法
func loadData(completion: (isSuccessed: Bool)->()) {
// 定義 url 與參數(shù)
let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
let params = [
"access_token": HMUserAccountViewModel.sharedUserAccount.accessToken!
]
HMNetworkTools.shareTools.request(.GET, url: urlString, params: params) { (result, error) -> () in
if error != nil {
print("加載失敗\(error)")
completion(isSuccessed: false)
return
}
// 加載成功
guard let statusesDict = result?["statuses"] as? [[String: AnyObject]] else {
return
}
// 字典轉(zhuǎn)模型
// 定義臨時(shí)數(shù)據(jù)
var tempArray = [HMStatus]()
for statusDict in statusesDict {
let status = HMStatus(dict: statusDict)
tempArray.append(status)
}
self.statuses = tempArray
completion(isSuccessed: true)
}
}
- 在
HMHomeTableViewController
中增加微博視圖模型屬性
/// 微博列表視圖模型
lazy var statusListViewModel = HMStatusListViewModel()
- 修改
loadData
函數(shù)
// MARK: - 加載數(shù)據(jù)
statusLiseViewModel.loadData { (isSuccessed) -> () in
if isSuccessed {
print("加載成功")
}else {
SVProgressHUD.showErrorWithStatus("網(wǎng)絡(luò)不好")
}
}
運(yùn)行測(cè)試王浴,印象:由視圖模型負(fù)責(zé)數(shù)據(jù)處理
顯示表格數(shù)據(jù)
- 定義可重用標(biāo)識(shí)符
/// 表格標(biāo)識(shí)符
private let HMStatusCellId = "HMStatusCellId"
- 在
viewDidLoad
中調(diào)用方法注冊(cè)可重用Cell
/// 設(shè)置tableView相關(guān)
private func setupTableView(){
// 注冊(cè)系統(tǒng)的cell
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: HMStatusCellId)
}
- 實(shí)現(xiàn)數(shù)據(jù)源函數(shù)
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusListViewModel.statuses?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(HMStatusCellId, forIndexPath: indexPath)
cell.textLabel?.text = statusListViewModel.statuses![indexPath.row].text
return cell
}
用戶模型
定義模型
/// 用戶模型
class HMUser: NSObject {
/// 用戶UID
var id: Int = 0
/// 友好顯示名稱
var name: String?
/// 用戶頭像地址(中圖),50×50像素
var profile_image_url: String?
/// 認(rèn)證類型 -1:沒(méi)有認(rèn)證梅猿,1:認(rèn)證用戶氓辣,2,3,5: 企業(yè)認(rèn)證,220: 達(dá)人
var verified: Int = 0
/// 會(huì)員等級(jí) 1-6
var mbrank: Int = 0
// MARK: - 構(gòu)造函數(shù)
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let keys = ["id", "name", "profile_image_url", "mbrank"]
return dictionaryWithValuesForKeys(keys).description
}
}
在 HMStatus
中針對(duì)用戶模型增加處理
- 增加屬性
/// 微博作者的用戶信息字段
var user: HMUser?
運(yùn)行測(cè)試袱蚓,會(huì)發(fā)現(xiàn) user 字段被 KVO 設(shè)置成了字典
- 修改
HMStatus
的構(gòu)造函數(shù)
override func setValue(value: AnyObject?, forKey key: String) {
// 判斷 key 是否是 "user"
if key == "user" {
user = HMUser(dict: value as! [String: AnyObject])
return
}
super.setValue(value, forKey: key)
}
自定義 cell
- 建立
HMStatusCell
自定義Cell
/// 微博 Cell
class HMStatusCell: UITableViewCell {
// MARK: 搭建界面
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
}
}
- 建立微博視圖模型
/// 微博視圖模型
class HMStatusViewModel: NSObject {
/// 微博模型
var status: Status?
/// 構(gòu)造函數(shù)
init(status: Status) {
self.status = status
}
}
- 添加視圖模型屬性
/// 微博視圖模型
var statusViewModel: HMStatusViewModel?
- 修改
HMStatusListViewModel
中的網(wǎng)絡(luò)代碼中字典轉(zhuǎn)模型部分
// 微博視圖模型數(shù)組
var statuses: [HMStatusViewModel]?
...
// 字典轉(zhuǎn)模型
if self.statuses == nil {
self.statuses = [HMStatusViewModel]()
}
// 字典轉(zhuǎn)模型
for dic in array {
self.statuses?.append(HMStatusViewModel(status: HMStatus(dictionary: dic)))
}
- 修改
HMHomeTableViewController
數(shù)據(jù)源方法
tableView.registerClass(HMStatusCell.self, forCellReuseIdentifier: HMStatusCellId)
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(HMStatusCellId, forIndexPath: indexPath) as! HMStatusCell
// 獲取微博的視圖模型
let statusModel = statusListViewModel.statuses![indexPath.row]
cell.textLabel?.text = statusModel.status?.user?.name
return cell
}
單元格分析
微博的單元格包含以下 6
種類型:
- 原創(chuàng)微博無(wú)圖
- 原創(chuàng)微博單圖
- 原創(chuàng)微博多圖
- 轉(zhuǎn)發(fā)微博無(wú)圖
- 轉(zhuǎn)發(fā)微博單圖
- 轉(zhuǎn)發(fā)微博多圖
自定義 Cell 中需要注意的
- 單圖會(huì)按照?qǐng)D片等比例顯示
- 多圖的圖片大小固定
- 多圖如果是4張钞啸,會(huì)按照
2 * 2
顯示 - 多圖其他數(shù)量,按照
3 * 3
九宮格顯示