08-首頁(yè)

首頁(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 九宮格顯示
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市体斩,隨后出現(xiàn)的幾起案子梭稚,更是在濱河造成了極大的恐慌,老刑警劉巖絮吵,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件弧烤,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蹬敲,警方通過(guò)查閱死者的電腦和手機(jī)暇昂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)伴嗡,“玉大人急波,你說(shuō)我怎么就攤上這事∧志浚” “怎么了幔崖?”我有些...
    開封第一講書人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)渣淤。 經(jīng)常有香客問(wèn)我赏寇,道長(zhǎng),這世上最難降的妖魔是什么价认? 我笑而不...
    開封第一講書人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任嗅定,我火速辦了婚禮,結(jié)果婚禮上用踩,老公的妹妹穿的比我還像新娘渠退。我一直安慰自己,他們只是感情好脐彩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開白布碎乃。 她就那樣靜靜地躺著,像睡著了一般惠奸。 火紅的嫁衣襯著肌膚如雪梅誓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評(píng)論 1 304
  • 那天佛南,我揣著相機(jī)與錄音梗掰,去河邊找鬼。 笑死嗅回,一個(gè)胖子當(dāng)著我的面吹牛及穗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绵载,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼埂陆,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼苛白!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起焚虱,我...
    開封第一講書人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤丸氛,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后著摔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡定续,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年谍咆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片私股。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡摹察,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出倡鲸,到底是詐尸還是另有隱情供嚎,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布峭状,位于F島的核電站克滴,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏优床。R本人自食惡果不足惜劝赔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胆敞。 院中可真熱鬧着帽,春花似錦、人聲如沸移层。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)观话。三九已至予借,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間匪燕,已是汗流浹背蕾羊。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留帽驯,地道東北人龟再。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像尼变,于是被迫代替她去往敵國(guó)和親利凑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子浆劲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點(diǎn)贊按鈕進(jìn)度條TabLayout圖標(biāo)下拉刷新...
    皇小弟閱讀 46,759評(píng)論 22 665
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件哀澈、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,103評(píng)論 4 62
  • 今日碰到一個(gè)很有意思的問(wèn)題:OC如何重寫(override) (P.S. 對(duì)原因不感興趣的讀者可以直接跳到文章最后...
    王萊恩閱讀 16,695評(píng)論 12 13
  • 只要我們能夠放棄對(duì)自己的過(guò)度關(guān)注牌借,便可以忠實(shí)地給別人多少的關(guān)懷。大自然既能適應(yīng)我們的長(zhǎng)處割按,也能適應(yīng)我們的弱點(diǎn)膨报。有些...
    初心_f755閱讀 153評(píng)論 0 0
  • 數(shù)算恩福 1.感恩媽媽,媽媽脾氣很好适荣,從來(lái)不罵人现柠,給了我一個(gè)很好的榜樣,謝謝媽媽弛矛,謝謝謝謝謝謝够吩! 2.感恩爸爸,以...
    lrryy閱讀 179評(píng)論 0 1