HTTPCodable

Build Status swift 4.2 osx | ubuntu | docker

HTTPCodable 允许你发送 HTTP 请求(使用 Codable 作为请求体),并获取一个 Codable 对象,它被 Future 包装返回。一图胜千言

struct Todo: Codable {
  var id: Int
  var userId: Int
  var title: String
  var completed: Bool
}

let url = "https://jsonplaceholder.typicode.com/todos"

Client.shared.get(url, as: [Todo].self).map { todos in
  // todos is an array of Todo objects
  return todos.filter { $0.completed }
}.whenFulfilled { completed in
  // completed is an array of completed todos
}

它严重依赖 Futures,并且所有请求都会返回 Future。

示例

查看 HTTPCodableTests 以获取更多示例,代码本身也具有很好的解释性。

import HTTPCodable

/// Our object
struct Todo: Codable {
  var id: Int
  var userId: Int
  var title: String
  var completed: Bool
}

/// You can define your ?query=string&s=foo as Codable structs
struct TodoQuery: Codable {
  var id: Int?
  var userId: Int?
  var completed: Bool?
}

Client.shared.baseUrl = "https://jsonplaceholder.typicode.com/"

// Simple GET
Client.shared.get("/todos", as: [Todo].self).whenFulfilled { todos in
  // todos is an array of Todo objects
}

// GET with query
Client.shared.get("/todos", as: [Todo].self, query: TodoQuery(id: nil, userId: 1, completed: false)).whenFulfilled { todos in
  // todos is an array of Todo objects, with userId=1 and completed=false
}

// Post
let data = Todo(id: 1, userId: 1, title: "Foo", completed: true)
Client.shared.post(data, to: "/todos", as: Todo.self).whenFulfilled { todo in
  // todo is our newly created todo
}

// Put
Client.shared.put(data, to: "/todos/1", as: Todo.self).whenFulfilled { todo in
  // todo is our updated todo
}

// Patch
Client.shared.patch(data, to: "/todos/1", as: Todo.self).whenFulfilled { todo in
  // todo is our patched todo
}

// Delete
struct EmptyResponse: Codable {}

Client.shared.delete("/todos/1", as: EmptyResponse.self).whenFulfilled { _ in
  // removed
}

入门指南

HTTPCodable 可以通过 Swift 包管理器或手动方式(目前来说)添加到你的项目中;

SPM

将 HTTPCodable 添加为依赖项

dependencies: [
    .package(url: "https://github.com/terwanerik/HTTPCodable.git", from: "0.1.0")
]

然后导入模块

import HTTPCodable

手动方式

下载其中一个发布版本,然后将 /Sources/HTTPCodable 文件夹拖入 Xcode 中。确保将 Futures 作为框架安装(例如通过 Carthage)

支持的平台

HTTPCodable 支持所有 Futures 支持的平台;也就是所有 Swift 3 及更高版本支持的平台。