1.打開Xcode新建項目MoyaDemo
2.選擇IOS 导俘,Single View Application 下一步
輸入項目名稱:MoyaDemo
安裝cocopods 考婴,新建podfile?
打開終端:cd 進(jìn)入項目文件夾
運(yùn)行: pod init 新建podfile文件
安裝Moya第三方庫:
platform :ios,'9.0'
use_frameworks!
target 'MoyaDemo' do
pod 'Moya'
end
在終端執(zhí)行命令 pod ?install
會提示執(zhí)行成功。關(guān)閉項目杆麸,重新使用.xcworkspace打開項目
封裝一個用于網(wǎng)絡(luò)訪問的工具類:NetworkTools
新建文件搁进,選擇Cocoa Toutch Class NetworkTools
下一步輸入 NetworkTools ,選擇繼承的類是NSObject 下一步
在NetworkToos 封裝所有的網(wǎng)絡(luò)請求昔头。
實現(xiàn)moya的方法饼问,遵循TargetType協(xié)議 ?增加一個方法,增加一個case?
import UIKit
import Moya
public enum NetworkTools {
case userList
}
extension NetworkTools : TargetType {
public var baseURL: URL {
return URL(string: "http://127.0.0.1:8000/api/")!
}
public var path: String{
switch self {
case .userList:
return "/users"
}
}
public var method: Moya.Method{
switch self {
case .userList:
return .get
}
}
public var parameters: [String : Any]?{
switch self {
case .userList:
return nil
}
}
public var parameterEncoding: ParameterEncoding{
switch self {
case .userList:
return URLEncoding.default
}
}
public var sampleData: Data{
switch self {
case .userList:
return "userList test data".data(using: String.Encoding.utf8)!
}
}
public var task: Task{
switch self {
case .userList:
return .request
}
}
}
用ObjectMapper 對JSON格式進(jìn)行解析
先安裝 ObjectMapper
pod 'ObjectMapper'
運(yùn)行pod 安裝命令:
新建Model文件:User揭斧,點(diǎn)擊新建莱革,選擇 Swift File
導(dǎo)入ObjectMapper庫峻堰,通過JSON字段來編寫解析字段:
參考:https://github.com/Hearst-DD/ObjectMapper? 編寫解析
在storyboard里拉一個按鈕,點(diǎn)擊測試獲取json解析
編寫方法:
import UIKitimport Moyaclass MainViewController: UIViewController {? ? ? ? ? ? @IBAction func getUser_btn(_ sender: UIButton) {? ? ? ? ? ? ? ? getUserList()? ? ? ? ? ? }? ? func getUserList()? {? ? ? ? ? ? ? ? let? provider = MoyaProvider()
provider.request(.userList) { (result) in
switch result {
case let .success(moyaResponse):
//將請求結(jié)果轉(zhuǎn)化成字典
let json = try!moyaResponse.mapJSON() as! [String:Any]
//實例化一個User的模型對象
if let jsonRespones =? UserListResponse(JSON:json ){
print(jsonRespones.count,jsonRespones.userList)
}
case.failure:
print("網(wǎng)絡(luò)錯誤")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
運(yùn)行提示網(wǎng)絡(luò)錯誤:
蘋果默認(rèn)https協(xié)議
參考文章: