TinyRequest is a handy Swift package of doing networking request, in a declarative way with Combine and chainning style.
File -> Add Packages
let users = try? await TinyRequest(url: URL(string: "https://www.some-url.com")!)
.set(method: "GET")
.set(header: ["token": "xxx"])
.set(body: Data())
.objectResponse(type: UserAccount.self)
TinyRequest(url: URL(string: "https://www.some-url.com")!)
.set(method: "GET")
.set(header: ["token":"xxx"])
.set(body: Data())
.objectPublisher(type: UserAccount.self)
.sink { completion in
// handle completion
} receiveValue: { userAccount in
// Do something
print("Account name is: \(userAccount.firstName) \(userAccount.lastName)")
}
struct UserAccount: Decodable {
let firstName: String
let lastName: String
let userId: String
}
let (data, response) = try await TinyRequest(url: URL(string: "https://www.some-url.com")!)
.set(method: "POST")
.set(header: ["token":"xxx"])
.set(body: Data())
.dataResponse()
TinyRequest(url: URL(string: "https://www.some-url.com")!)
.set(method: "POST")
.set(header: ["token":"xxx"])
.set(body: Data())
.dataPublisher()
.sink { completion in
// handle completion
} receiveValue: { data in
// Do something with the data object
}
TinyRequest
with more optionslet request = TinyRequest(request: URLRequest(url: URL(string: "xxx")!),
session: URLSession(configuration: /* */)
decoder: JSONDecoder())
TinyServiceProtocol
https://www.some-fake-cloud-file-storage.com
GET
items/{id}
(id
is a String
type)200
Content-Type: application/json
[
{
"id": "file-item-id-1",
"isDir": true,
"modificationDate": "2022-11-05 09:14 CET",
"name": "Documents",
"parentId": "file-item-id-2"
},
{
"contentType": "image/jpg",
"id": "file-item-id-3",
"isDir": false,
"modificationDate": "2022-11-05 09:51 CET",
"name": "picture-3.jpg",
"parentId": "file-item-id-2",
"size": 200000
}
]
https://www.some-fake-cloud-file-storage.com
DELETE
items/{id}
(where id
is a String
type)204
if sccessfully deletedWe can define a FileService
confirming to TinyServiceProtocol
like these:
enum FileService {
case getItem(String)
case deleteItem(String)
}
extension FileService: TinyServiceProtocol {
public var baseUrl: String {
"https://www.some-fake-cloud-file-storage.com"
}
public var urlPath: String {
switch self {
case .getItem(let itemId),
.deleteItem(let itemId):
return "/items/\(itemId)"
}
}
public var queryItems: [URLQueryItem]? {
nil
}
public var method: String {
switch self {
case .getItem:
return "GET"
case .deleteItem:
return "DELETE"
}
}
public var header: [String : String]? {
nil
}
public var body: Data? {
nil
}
public var decoder: JSONDecoder {
JSONDecoder()
}
}
public struct FileItem: Decodable {
public let id: String
public var parentId: String?
public let name: String
public let isDir: Bool
public var contentType: ContentType?
public var size: Int?
}
FileService
in a ViewModel
:import TinyRequest
class ViewModel {
func getFile(itemId: String) async {
let fileItems = try? await FileService.getItem(itemId)
.asyncObject(type: [FileItem].self)
// Do something with fileItems
}
func deleteFile(itemId: String) async {
let (_, response) = try? await FileService.deleteItem(itemId)
.asyncDataResponse()
if let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 204 {
// Delete successfully
}
}
}
import TinyRequest
import Combine
class ViewModel {
private var cancellables: [AnyCancellable] = []
func getFile(itemId: String) {
FileService.getItem(itemId)
.objectPublisher(type: [FileItem].self)
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
// TODO
} receiveValue: { [weak self] items in
// TODO
}
.store(in: &cancellables)
}
func deleteFile(itemId: String) {
FileService.deleteItem(itemId)
.responsePublisher()
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
// TODO
} receiveValue: { [weak self] response in
if let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 204 {
// Delete successfully
}
}
.store(in: &cancellables)
}
}
link |
Stars: 5 |
Last commit: 3 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics