创建swift的文件HttpRequestFile
import Foundation
enum HttpRequest {
case shujuList(parameter:Dictionary<String, Any>) //带一堆参数的
case othetRequest(str:String) //带一个参数的请求
case requestCityList //不带参数的请求
}
创建swift的文件HttpRequestExtension 实现TargetType的协议方法
import Foundation
import Moya
/*
遵循mayo协议,实现方法
*/
extension HttpRequest : TargetType{
//服务器地址
var baseURL: URL {
return URL(string:"https:xxxxxxx.xxx")!
}
//各个请求的具体路径
var path: String {
switch self {
case .shujuList:
return "/ArticleList"
case .othetRequest:
return "/someOtherPath"
default:
return "/requestCityList"
}
}
//请求方式
var method: Moya.Method {
switch self {
case .shujuList:
return .post
default:
return .get
}
}
//请求任务事件(这里附带上参数)
var task: Task {
var param:[String:Any] = [:]
switch self {
case let .shujuList(parameter):
param = parameter
case let .othetRequest(str):
param["str"] = str
default:
//不需要传参数的走这里
return .requestPlain
}
return .requestParameters(parameters: param, encoding: URLEncoding.default)
}
//是否执行Alamofire验证
public var validate: Bool {
return false
}
//这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
}
//设置请求头
public var headers: [String: String]? {
return nil
}
}
ViewController的实现请求
import UIKit
import Moya
import SwiftyJSON
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let provide = MoyaProvider<HttpRequest>()
provide.request(.requestCityList) { Result in
switch Result {
case let .success(response):
//数据解析
let json = JSON(response.data)
print(json)
case let .failure(error):
print(error)
}
}
}
}