copinism-ios/copinism/utils/Http.swift
2024-06-07 16:04:27 +08:00

56 lines
1.7 KiB
Swift

import Foundation
import Alamofire
struct EmptyParams: Encodable {}
struct HTTPBinResponse<T: Decodable>: Decodable {
let code: Int
let data: T
let message: String
}
func makeAlamofireRequest<T: Decodable,Parame: Encodable>(api: String,
method: HTTPMethod = .get,
param: Parame? = nil,
completion: @escaping (Result<HTTPBinResponse<T>, AFError>) -> Void) {
var headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type":"application/json"
]
let loginStatus = checkLoginStatus()
if loginStatus.login {
headers.add(name: "Authorization", value: loginStatus.token)
}
AF.request(api, method: method, parameters: param, encoder: JSONParameterEncoder.default,headers: headers).validate().responseDecodable(of: HTTPBinResponse<T>.self) { response in
completion(response.result)
}
}
func uploadFile<T: Decodable>(api: String,file: Data,progressHandler: @escaping (Double) -> Void,completion: @escaping (Result<HTTPBinResponse<T>, AFError>) -> Void) {
var headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type":"application/octet-stream"
]
let loginStatus = checkLoginStatus()
if loginStatus.login {
headers.add(name: "Authorization", value: loginStatus.token)
}
print(api)
AF.upload(file, to: api,headers: headers)
.uploadProgress { progress in
progressHandler(progress.fractionCompleted)
}
.validate().responseDecodable(of: HTTPBinResponse<T>.self) { response in
completion(response.result)
}
}