OUR BLOG

27 Sep 2020

Alamofire 5 iOS 教程

Alamofire 5 iOS 教程 新建一个Xcode项目记住目录位置,首先用mac的终端进入目录位置,使用语句pod init 初始化 pod

pods 中加入

use_frameworks!
pod 'Alamofire', '~> 5.2'

然后pod install
成功后在需要使用的位置上加入 import Alamofire

自己写的fetchAll Posts

public func fetchAllPosts(){

var prefs:UserDefaults = UserDefaults.standard
let tokenadmin = prefs.value(forKey: "TOKENADMIN") as! String

let bearertoken:String = "Bearer "+tokenadmin
let headers :HTTPHeaders = [
"Authorization": bearertoken
]
AF.request(Global.REQUESTUSER, method: .get ,encoding: JSONEncoding.default, headers: headers).responseDecodable(of:[Temp].self) { (response) in
print(response)
guard let temps = response.value else { return }
//print(temps)

}
}

对应的json

[
{
“id”: 86,
“date”: “2020-09-26T11:22:19”,
“date_gmt”: “2020-09-26T11:22:19”,
“guid”: {
“rendered”: “http://www.vwve.com/?p=86”
},
“modified”: “2020-09-26T11:22:20”,
“modified_gmt”: “2020-09-26T11:22:20”,
“slug”: “dfasfdf”,
“status”: “publish”,
“type”: “post”,
“link”: “http://www.vwve.com/2020/09/26/dfasfdf/”,
“title”: {
“rendered”: “dfasfdf”
},
“content”: {
“rendered”: “”,
“protected”: false
},
“excerpt”: {
“rendered”: “

excerpt

\n”,
“protected”: false
},
“author”: 1,
“featured_media”: 0,
“comment_status”: “open”,
“ping_status”: “open”,
“sticky”: false,
“template”: “”,
“format”: “standard”,
“meta”: {
“location”: “sbnu7654”
},
“categories”: [
1
],
“tags”: [],

}

]

解析

struct Temp: Decodable {

let id :Int
let slug:String
enum CodingKeys: String, CodingKey {
case id
case slug = “slug”

}
}

admin