導入三方
pod 'Moya/RxSwift', '~> 11.0' pod 'SwiftyJSON', '~> 4.0'
配置文件
import UIKit
import Moya
import SwiftyJSON
import RxSwift
//請求分類
public enum netTool {
case zen
case userProfile(String)
}
// MARK: - get請求 https://api.github.com/zen https://api.github.com/users/ashfurrow
////請求的配置
extension netTool: Moya.TargetType {
//服務器的地址
public var baseURL: URL {
return URL(string: "https://api.github.com")!
}
var parameterEncoding: ParameterEncoding {
return JSONEncoding.default
}
//請求的路徑
public var path: String {
switch self {
case .zen:
return "/zen"
case .userProfile(let name):
return "/users/\(name)"
}
}
//請求的方法
public var method: Moya.Method {
return .get
}
//這個是做單元測試的數據,不用管
public var sampleData: Data {
return "Test data".data(using: .utf8)!
}
//請求的任務時間
public var task: Moya.Task {
switch self {
default:
return .requestPlain
}
}
//請求頭配置
public var headers: [String : String]? {
return nil
}
}
簡單的使用,建議導入三方的json解析器,完成解析
private let dispose = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let provider = MoyaProvider<netTool>()
provider.rx.request(.userProfile("ashfurrow")).subscribe{
(event) -> Void in
print("*************\(event)")
switch event {
case .success(let response):
print("?????")
do {
let info = try response.mapJSON()//返回的數據解析成 JSON
print(info)
} catch {
}
break
default:
break
}
}.disposed(by: dispose)
}
