SmartNet
SmartNet 是一个用 Swift 编写的 HTTP 网络库,旨在使网络尽可能简单。
特性
- 易于配置
- 支持请求类型: Encodable、Dictionary、String
- 支持响应类型: Decodable、String、Data、Void
- 支持查询参数类型: Encodable、Dictionary
- iOS 13+ Combine 支持
- 轻量级且易于操作的网络接口
- "可信域名" 列表以绕过 SSL 认证挑战(不推荐使用)
安装
Swift 包管理器
Swift 包管理器是一个用于自动化分发 Swift 代码的工具,并集成到 swift
编译器中。
在 Xcode 11 及以上版本中,选择“文件 > 包 > 添加包依赖 > 输入此项目的 URL”
https://github.com/vetrek/SmartNet.git
CocoaPods
pod 'SmartNet'
示例
-
网络默认配置
NetworkConfiguration 用于定义在每次调用中将使用的默认设置。
如果 Endpoint 以 "useEndpointHeaderOnly: true" 初始化,则忽略 NetworkConfiguration 的头部。
基础
let config = NetworkConfiguration(baseURL: URL(string: "https://api.example.com")!)
let network = SmartNet(config: config)
高级
let config = NetworkConfiguration(
baseURL: URL(string: "https://api.publicapis.org")!,
headers: ["Content-Type": "application/json"],
queryParameters: ["userid": "xxxxxx"],
trustedDomains: ["api.publicapis.org"],
requestTimeout: 120
)
let network = SmartNet(config: config)
-
创建一个端点
GET
let endpoint = Endpoint<Person>(
path: "person",
queryParameters: QueryParameters(
parameters: [
"name": "Jhon",
"age": 18
]
)
)
等效于 https://api.example.com/person?name=Jhon&age=18
POST
let endpoint = Endpoint<Person>(
path: "person",
method: .post,
body: HTTPBody(
encodable: PersonRequst(
name: "Jhon",
age: 18
)
)
)
等效于包含以下正文的 https://api.example.com/person
{
"name": "Jhon",
"age": 18
}
API CALL
- 使用闭包
network.request(with: endpoint) { (response) in
switch response.result {
case .success(let person):
print("Success! \(person.name)")
case .failure(let error):
print(error.localizedDescription)
}
}
- 使用Combine
var subscriptions = Set<AnyCancellable>()
network.request(with: endpoint)?
.sink(
receiveCompletion: { (response) in
if case .failure(let error) = response {
print(error.localizedDescription)
}
},
receiveValue: { (person) in
print("Success! \(person.name)")
}
)
.store(in: &subscriptions)
信息
受SENetworking (https://github.com/kudoleh/SENetworking)启发的项目。