Netlink 1.0.0

Netlink 1.0.0

Rohit Kumar 维护。



Netlink 1.0.0

  • 作者::
  • Rohit Kumar

Netlink

一个用于进行 HTTP 网络调用的 iOS SDK。
Netlink 是一个用于使用 Swift 进行 HTTP 网络调用的轻量级 CocoaPod。它提供了简单的方法来执行 GET 和 POST 请求,将响应解析为通用的 Swift 模型或结构体。

安装

您可以使用 CocoaPods 将 Netlink 集成到项目中。将以下行添加到您的 Podfile 中:

pod 'Netlink', '~> 1.0'

然后,从终端运行 pod install。

用法

GET 请求

要使用 Netlink 执行 GET 请求,调用 get 方法

NetLink.get(urlString: "https://example.com/api/data", queryItems: ["param": "value"], headers: ["Authorization": "Bearer token"])
    .sink(receiveCompletion: { completion in
        // Handle completion (success or failure)
    }, receiveValue: { response: YourModelType in
        // Handle successful response
    })
    .store(in: &cancellables)

POST 请求

要使用 Netlink 执行 POST 请求,调用 post 方法

NetLink.post(urlString: "https://example.com/api/post", queryItems: nil, headers: nil, payload: ["key": "value"])
    .sink(receiveCompletion: { completion in
        // Handle completion (success or failure)
    }, receiveValue: { response: YourModelType in
        // Handle successful response
    })
    .store(in: &cancellables)

示例:Todo 模型

以下是如何使用 Netlink 与 Todo 模型一起使用的示例

import Foundation
import Combine

class Apiservice {
    
    // Function to fetch data via GET request
    func getData<T>(urlString: String, responseType: T.Type) -> Future<T, Error> where T: Codable {
        return NetLink.get(urlString: urlString)
    }
    
    // Function to send data via POST request
    func sendData<T>(urlString: String, payload: [String: Any], responseType: T.Type) -> Future<T, Error> where T: Codable {
        return NetLink.post(urlString: urlString, payload: payload)
    }
}

以下是这些函数的用法

struct TodoItem: Codable {
    let id: Int
    let title: String
    let completed: Bool
}


class SomeClass {
    private var storage = Set<AnyCancellable>()
    private let apiService = Apiservice()
    
    func fetchTodoItem() {
        apiService.getData(urlString: "https://jsonplaceholder.typicode.com/todos/1", responseType: TodoItem.self)
            .receive(on: DispatchQueue.main)
            .clubIntoResult()
            .sink { result in
                switch result {
                case .success(let todoItem):
                    // Handle successful response
                    print(todoItem)
                case .failure(let error):
                    // Handle error
                    print(error)
                }
            }
            .store(in: &storage)
    }
    
    func createTodoItem() {
        let newTodo: [String: Any] = ["title": "New Todo", "completed": false]
        apiService.sendData(urlString: "https://jsonplaceholder.typicode.com/todos", payload: newTodo, responseType: TodoItem.self)
            .receive(on: DispatchQueue.main)
            .clubIntoResult()
            .sink { result in
                switch result {
                case .success(let createdTodo):
                    // Handle successful response
                    print(createdTodo)
                case .failure(let error):
                    // Handle error
                    print(error)
                }
            }
            .store(in: &storage)
    }
}

注意

Netlink 提供了一个 Publisher 扩展 clubIntoResult()
clubIntoResult() 操作符在 Combine 中将 Publisher 的输出流转换为 Result 类型,封装成功和失败的情况,简化了统一的结果处理。

public extension Publisher {
    /// Puts success and failure streams in `Result`. In some publishers like `Future` both sink methods were required to get sucess and failure values
    /// to avoid that, this operator clubs both the streams in Result type so that you can get both success and failure as success wrapped in `Result`
    func clubIntoResult() -> AnyPublisher<Result<Output, Failure>, Never> {
        self
            .map { .success($0) }
            .catch { Just(.failure($0)) }
            .eraseToAnyPublisher()
    }
}