SwiftRestAPIClient 2.0.4

SwiftRestAPIClient 2.0.4

Hasan Atay 维护。



  • kha26

SwiftRestAPIClient

CI Status Version License Platform

SwiftRestAPIClient 是一个用 Swift 编写的框架,它使您能够轻松地为您的应用程序构建 Rest API 客户端。

  • [特性] (#features)
  • [基本用法] (#example-usage)

特性

  • 客户端的基本骨架系统
  • 请求和响应的泛型类型
  • 错误处理
  • 客户端配置

示例用法

首先,您需要通过实现 APIConfiguration 协议来配置 API 客户端,该协议包括以下内容

/// Base URL of the API
var baseUrl: String { get }

/// The default HTTP Headers that will be sent for every request
var headers: [String: String] { get }

// The minimum acceptable status code for the backend
var minStatusCode: Int { get }

// The maximum acceptable status code for the backend
var maxStatusCode: Int { get }

例如: class MyConfiguration: APIConfiguration

然后,在 AppDelegate.swift 中设置客户端的配置

import SwiftRestAPIClient

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    APIClient.shared.configuration = MyConfiguration()
    return true
}

现在,配置已经设置,是时候设置请求了。这很简单,您只需要了解 APIClient、APIRequest 和 APIResponse 之间的协同工作方式。客户端向服务器发送请求,并返回在请求中声明的响应。APIClient 已经是一个正在运行的类,因此您不需要对该类进行子类化。让我们以一个示例后端应用程序为例,该应用程序有用户,用户可以创建帖子评论。我们可以有如下端点:GET /posts POST /posts POST /users/login

在实现请求之前,我们需要确定我们想要接收什么样的响应。通常,一个请求返回一个对象或对象数组。有两个类实现了 APIResponse 协议:ObjectResponse 和 ArrayResponse。如您所见,其中一个用于返回对象,另一个用于返回对象数组。这些对象必须实现 Codable 协议。Codable 是 Swift 4 中推出的 Swift 库。如果您不知道如何使用它,建议您查看这篇指南

对于类似于 GET /posts?limit=5&offset=10 的 GET 请求,您可以按以下方式实现 APIRequest 协议

class GetPostsRequest {
    typealias Response = ArrayResponse<Post>

    var resourceName: String {
        return "/posts"
    }

    var method: APIMethod {
        return .get
    }

    var parameters: [String: Any] = [:]
    
    init(limit: Int, offset: Int) {
        parameters["limit"] = limit
        parameters["offset"] = offset
    }
}

对于类似于 POST /posts/5/comments 的 POST 请求,以创建一个评论对象,您可以执行以下操作

class PostPostRequest {
    typealias Response = ObjectResponse<Comment>

    var resourceName: String {
        return "/post/\(postId)/comments"
    }

    var method: APIMethod {
        return .post
    }

    var parameters: [String: Any] = [:]
    
    var postId: Int
    
    init(post: Post) {
        self.postId = post.id
        parameters["message"] = post.message
        parameters["createdBy"] = post.user.id
    }
}

APIRequest 还有两个其他功能:头和回调。例如,如果您发送一个作为 POST 的登录请求,您可能希望添加一个基本认证头并保存从服务器获取的结果数据(例如令牌)。实现此操作非常简单

class UserLoginRequest {
    
    private var username: String
    private var password: String
    
    init(username: String, password: String) {
        self.username = username
        self.password = password
    }
    
    var headers: HTTPHeaders {
        var headers: HTTPHeaders = [:]
        if let authorizationHeader = Request.authorizationHeader(user: username, password: password) {
            headers[authorizationHeader.key] = authorizationHeader.value
        }
        return headers
    }
    
    func callback(item: UserLoginRequest.Response) {
        // item.result is the response object
        // here you can save it like
        // this function is called after the request is completed
        Keychain.save(item.result)
    }
}

最后,调用这些请求非常简单

let request = APIClient.shared.send(GetPostsRequest(limit: 10, offset: 5), objectBlock: { (response) in
    if (reponse.success) {
        // do something with response.result
        // you will see that response.result is the type that you want
    } else {
        // handle response.error
    }
})

示例

要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install

要求

安装

SwiftRestAPIClient 可以通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中

pod 'SwiftRestAPIClient'

作者

kha26, [email protected]

许可协议

SwiftRestAPIClient 在 MIT 许可协议下可用。有关更多信息,请参阅 LICENSE 文件。