Requestify
是一个使用 Alamofire 构建的灵活且可重用的网络请求工具。 它允许开发者轻松构建和发送 HTTP 请求,并具有可自定义的方法、标头、参数和日志记录选项。
要创建请求,请使用 RequestBuilder 结构体,通过链式调用配置方法。
import Requestify
let requestify = Requestify()
.setURL("https://jsonplaceholder.typicode.com/posts")
.setMethod(.get)
.setPrintLog(true)
配置完请求后,使用 Swift 的 async/await 发送请求并处理响应。
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
Task {
do {
let posts: [Post] = try await requestify.request([Post].self)
print("Posts: \(posts)")
} catch {
print("Error: \(error)")
}
}
您可以发送自定义标头和参数到请求中。
let customHeaders: HTTPHeaders = [
"Authorization": "Bearer token"
]
let parameters = Params()
.add("userId", value: 1)
.build()
let requestify = Requestify()
.setURL("https://jsonplaceholder.typicode.com/posts")
.setMethod(.post)
.setHeaders(customHeaders)
.setParameters(parameters)
.setPrintResponse(false)
如果您需要一个原始的 HTTPURLResponse,而无需解码 body,请使用。
Task {
do {
let response = try await requestify.requeust()
print("Response status code: \(response.statusCode)")
} catch {
print("Error: \(error)")
}
}
对于上传文件或图像,Requestify 提供了一个简单的接口来创建 multipart 请求。
import UIKit
let post = Post()
let requestify = Requestify()
.setURL("https://yourapi.com/upload")
.setMethod(.post)
.addObject(post, withName: "post")
.addImages([UIImage(named: "example")], withName: "file")
.setPrintResponse(false)
Task {
do {
let response: YourResponseType = try await requestify.upload(YourResponseType.self)
print("Upload successful: \(response)")
} catch {
print("Error: \(error)")
}
}
您可以使用 setPrintLog 和 setPrintResponse 来控制请求和响应的日志记录。
.setPrintLog(true)
.setPrintResponse(false)