moya是对alamofire的封装,我们不用自己去封装了。
基础用法:
第一步。 定义一个api枚举。封装请求入参
enum HomeAPI {
case zen
case showUser(id: Int)
case createUser(firstName: String, lastName: String)
case updateUser(id: Int, firstName: String, lastName: String)
case showAccounts
case guessYouLike
}
第二步 扩展HomeAPI,实现 TargetType
extension HomeAPI: TargetType {
var baseURL: URL { return URL(string: "https://api.mamahao.com")! }
var path: String {
switch self {
case .zen:
return "/zen"
case .showUser(let id), .updateUser(let id, _, _):
return "/users/\(id)"
case .createUser(_, _):
return "/users"
case .showAccounts:
return "/accounts"
case .guessYouLike:
return "shop/basic/guessYouLike.htm"
}
}
var method: Moya.Method {
switch self {
case .zen, .showUser, .showAccounts, .guessYouLike:
return .get
case .createUser, .updateUser:
return .post
}
}
var task: Task {
switch self {
case .zen, .showUser, .showAccounts, .guessYouLike: // Send no parameters
return .requestPlain
case let .updateUser(_, firstName, lastName): // Always sends parameters in URL, regardless of which HTTP method is used
return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: URLEncoding.queryString)
case let .createUser(firstName, lastName): // Always send parameters as JSON in request body
return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: JSONEncoding.default)
}
}
var sampleData: Data {
switch self {
case .zen:
return "Half measures are as bad as nothing at all.".utf8Encoded
case .showUser(let id):
return "{\"id\": \(id), \"first_name\": \"Harry\", \"last_name\": \"Potter\"}".utf8Encoded
case .createUser(let firstName, let lastName):
return "{\"id\": 100, \"first_name\": \"\(firstName)\", \"last_name\": \"\(lastName)\"}".utf8Encoded
case .updateUser(let id, let firstName, let lastName):
return "{\"id\": \(id), \"first_name\": \"\(firstName)\", \"last_name\": \"\(lastName)\"}".utf8Encoded
case .showAccounts, .guessYouLike:
// Provided you have a file named accounts.json in your bundle.
guard let url = Bundle.main.url(forResource: "accounts", withExtension: "json"),
let data = try? Data(contentsOf: url) else {
return Data()
}
return data
}
}
var headers: [String: String]? {
return ["Content-type": "application/json"]
}
}
第三部发送请求
func loadData() {
let provider = MoyaProvider<HomeAPI>()
provider.request(HomeAPI.createUser(firstName: "fish", lastName: "ycx")) { (response) in
}
}