SmartNet is an HTTP networking library written in Swift that aims to make networking as easy as possible.
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift
compiler.
In Xcode 11+ select File > Packages > Add Package Dependency > Enter this project's URL:
https://github.com/vetrek/SmartNet.git
pod 'SmartNet'
NetworkConfiguration is used to define defaults settings that are going to be used in every call.
If the Endpoint is initialized with "useEndpointHeaderOnly: true" the NetworkConfiguration headers will be ignored.
Base
let config = NetworkConfiguration(baseURL: URL(string: "https://api.example.com")!)
let network = SmartNet(config: config)
Advanced
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)
let endpoint = Endpoint<Person>(
path: "person",
queryParameters: QueryParameters(
parameters: [
"name": "Jhon",
"age": 18
]
)
)
Equivalent of 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
)
)
)
Equivalent of https://api.example.com/person with the following body:
{
"name": "Jhon",
"age": 18
}
API CALL
do {
let response = try await network.request(with: endpoint)
print(response)
} catch {
print(error)
}
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)
network.request(with: endpoint) { (response) in
switch response.result {
case .success(let person):
print("Success! \(person.name)")
case .failure(let error):
print(error.localizedDescription)
}
}
link |
Stars: 4 |
Last commit: 3 days ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics