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
}
})
}
}

うずまき ナルト