iOS & 網(wǎng)絡(luò)請求Alamofire及數(shù)據(jù)轉(zhuǎn)換ObjectMapper

Alamofire & AlamofireObjectMapper

對于掌握一門新技術(shù)而言,請求接口數(shù)據(jù)Alamofire及數(shù)據(jù)轉(zhuǎn)換ObjectMapper是必不可少的。

而技術(shù)選型只是大致調(diào)研了下,然后集成到項目中,多了解多對比,后面再優(yōu)化或者替換。

因為用了Alamofire ,所以數(shù)據(jù)轉(zhuǎn)換ORM這塊選用了更適用的 AlamofireObjectMapper

作為一個小白,仿佛一切又回到了起點,用了太久的GraphQL自動生成POJO,從不用擔(dān)心ORM這塊的我,終于又要手敲轉(zhuǎn)換類了。

小白總要將就,先使用AlamofireObjectMapper手動生成POJO,后面有合適的再換

1.修改Podfile文件,安裝相應(yīng)庫

Pod 增加配置

執(zhí)行安裝命令

arch -x86_64 Pod install
安裝成功

2.生成轉(zhuǎn)換類

// 接口返回數(shù)據(jù)結(jié)構(gòu)
{
     "result": {
         "songs": [
             {
                 "id": 347230,
                 "name": "海闊天空",
                 "artists": [
                     {
                         "id": 11127,
                         "name": "Beyond",
                         "picUrl": null,
                         "alias": [],
                         "albumSize": 0,
                         "picId": 0,
                         "img1v1Url": "http://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg",
                         "img1v1": 0,
                         "trans": null
                     }
                 ],
                 "duration": 326000,
                 "copyrightId": 7002,
                 "status": 0,
                 "alias": [],
                 "rtype": 0,
                 "ftype": 0,
                 "transNames": [
                     "Boundless Oceans, Vast Skies"
                 ],
                 "mvid": 376199,
                 "fee": 1,
                 "rUrl": null,
                 "mark": 8192
             }
         ],
         "hasMore": true,
         "songCount": 524
     },
     "code": 200
 }

字段太多了,只選擇幾個典型的進行轉(zhuǎn)換

//
//  SongsResponse.swift
//  AlamofireDemo
//
//  Created by Jake on 2021/7/20.
//

import ObjectMapper

/**
  請求轉(zhuǎn)換基類 ( 竟然需要手寫,后面要找自動生成的插件 )
  map 可以跨越無用的中間類,例如 :name <- map["result.songs.1.name"]
 */

class ResultBase: Mappable {
    
    var songs : [Songs]?
    var code : Int?
//    var name : String?
    
    required init?(map: Map) {
    
    }
    
    func mapping(map: Map) {
        songs <- map["result.songs"]
        code <- map["code"]
//        name <- map["result.songs.1.name"]
    }
    
}

class Songs:  ResultBase{

    var id :Int?
    var name : String?
    var imageUrl : String?

    required init?(map: Map) {
        super.init(map: map)

    }

    override func mapping(map: Map) {
        super.mapping(map: map)
        id <- map["id"]
        name <- map["name"]
        // 默認取第一個 artists 的 img1v1Url
        imageUrl <- map["artists.0.img1v1Url"]
    }

}

注意:類的繼承與super的調(diào)用;還有子類名要與接口返回一致。
Map的匹配規(guī)則:可跳躍用不到的屬性,但是一定要注意與字段名一致。

// 跳躍舉例如下
songs <- map["result.songs"]
imageUrl <- map["artists.0.img1v1Url"]

3.網(wǎng)絡(luò)請求

Alamofire 封裝了很多返回值的格式,此處用 responseObject ,原因上面說過了

    override func viewDidLoad() {
        super.viewDidLoad()
        // 簡陋的網(wǎng)絡(luò)請求,后面要封裝
        _ = Alamofire.request("http://192.168.10.3:3000/search?keywords=%E6%B5%B7%E9%98%94%E5%A4%A9%E7%A9%BA")
            .responseObject(completionHandler: { (response: DataResponse<ResultBase>) in
                switch response.result {
                case let .success(data):
                    if data.songs != nil {
                     self.queryData = data.songs!
                     self.creatTableView()
                    }

                break
                case let .failure(data):
                    print(data.localizedDescription)
                break
                }
            })
        
    }

4.頁面展示

Table View 展示列表數(shù)據(jù)

5.附上簡陋的VC代碼,待整理。

//
//  ViewController.swift
//  AlamofireDemo
//
//  Created by Jake on 2021/7/19.
//

import UIKit
import Alamofire
import AlamofireObjectMapper

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView!
    var queryData:[Songs] = []
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.queryData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let id = self.queryData[indexPath.row].id ?? 0
        let name = self.queryData[indexPath.row].name ?? ""
        cell.textLabel?.text = name + "> > id \(id)"
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        self.queryData.count
    }
    
    /// 創(chuàng)建表格
     func creatTableView() {
         self.tableView = ({
             let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), style: .plain)
             tableView.delegate = self
             tableView.dataSource = self
             tableView.separatorStyle = .none
             tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
             self.view.addSubview(tableView)
             return tableView
         })()
     }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 簡陋的網(wǎng)絡(luò)請求,后面要封裝
        _ = Alamofire.request("http://192.168.10.3:3000/search?keywords=%E6%B5%B7%E9%98%94%E5%A4%A9%E7%A9%BA")
            .responseObject(completionHandler: { (response: DataResponse<ResultBase>) in
                switch response.result {
                case let .success(data):
                    if data.songs != nil {
                     self.queryData = data.songs!
                     self.creatTableView()
                    }
                break
                case let .failure(data):
                    print(data.localizedDescription)
                break
                }
            })
    }
}

うずまき ナルト
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在實際項目開發(fā)過程中,很多時候移動終端設(shè)備都要與服務(wù)器進行數(shù)據(jù)交互。兩者之間的數(shù)據(jù)格式通常為 JSON 和 XML...
    Anenn閱讀 11,517評論 6 22
  • 用到的組件 1、通過CocoaPods安裝 2、第三方類庫安裝 3、第三方服務(wù) 友盟社會化分享組件 友盟用戶反饋 ...
    SunnyLeong閱讀 15,134評論 1 180
  • 表情是什么,我認為表情就是表現(xiàn)出來的情緒。表情可以傳達很多信息。高興了當(dāng)然就笑了,難過就哭了。兩者是相互影響密不可...
    Persistenc_6aea閱讀 129,400評論 2 7
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險厭惡者,不喜歡去冒險,但是人生放棄了冒險,也就放棄了無數(shù)的可能。 ...
    yichen大刀閱讀 7,541評論 0 4

友情鏈接更多精彩內(nèi)容