SNHttpRequest
SNHttpRequest
是一个在 Swift 中围绕 NSURLSession
的轻量级封装,用于简化 HTTP 请求。
要求
- iOS 11.0+
- Xcode 10.2+
- Swift 5+
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理工具。有关使用和安装说明,请访问其网站。要使用 CocoaPods 在 Xcode 项目中集成 Alamofire,请将它指定在 Podfile
中
pod 'SNHttpRequest'
功能
- 便捷的闭包 API
- 参数编码
- 内置JSON请求序列化
- 简洁的代码库。
首先需要导入框架。请参考安装指南了解如何将框架添加到您的项目中。
import SNHttpRequest
示例
HTTP方法
所有的常见HTTP方法都可作为方便的函数使用。
GET
最基本的请求。默认情况下,响应会返回一个Date对象。
RequestService.getRequest(url: "https://google.com") { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
RequestService.getRequest(url: "your endpoint", token: "your token", authType: .bearerToken) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
}
POST
let postData = ["param1":"value1","param2":"value2"]
RequestService.postRequest(url: "your endpoint", postData: postData, method: .post) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
RequestService.postRequest(url: "your endpoint",token: "token",authType: .bearerToken, postData: postData, method: .post) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
PUT
let postData = ["param1":"value1","param2":"value2"]
RequestService.postRequest(url: "your endpoint", postData: postData, method: .put) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
RequestService.postRequest(url: "your endpoint",token: "token",authType: .bearerToken, postData: postData, method: .put) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
DELETE
let postData = ["param1":"value1","param2":"value2"]
RequestService.postRequest(url: "your endpoint", postData: postData, method: .delete) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}
RequestService.postRequest(url: "your endpoint",token: "token",authType: .bearerToken, postData: postData, method: .delete) { (response) in
switch response
{
case .Success(let response):
print(response)
case .ApiError(let apiError):
print(apiError)
case .Error(let error):
print(error)
}
}