由 Swift 3 编写的简单 HTTP 客户端。
安装
Carthage
Carthage 是一种去中心化的依赖管理器,它构建您的依赖并提供二进制框架。
您可以使用以下命令通过 Homebrew 安装 Carthage
$ brew update
$ brew install carthage
要使用 Carthage 将 SwiftClient
集成到您的 Xcode 项目中,请在 Cartfile
文件中指定它。
github "theadam/SwiftClient" ~> 3.0.4
运行 carthage update
命令以构建框架,然后将构建好的 SwiftClient.framework
拖动到您的 Xcode 项目中。
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装它:
$ gem install cocoapods
要使用 CocoaPods 将 SwiftClient
集成到您的 Xcode 项目中,请在 Podfile
文件中指定它。
platform :ios, '9.0'
use_frameworks!
pod 'SwiftClient', '~> 3.0.4'
然后,运行以下命令:
$ pod install
手动操作
- 如果您使用的是 git,请使用以下命令将 SwiftClient 作为子模块添加:
git submodule add https://github.com/theadam/SwiftClient.git
。否则,在项目文件夹中使用git clone https://github.com/theadam/SwiftClient.git
下载项目。 - 在 Xcode 中,右键单击蓝色项目图标,选择“添加文件到...”,然后选择 SwiftClient/SwiftClient.xcodeproj 并点击添加。
- 通过单击蓝色项目图标,然后在侧边栏的“Target”标题下选择应用程序目标来导航到目标配置窗口。
- 在该窗口的顶部标签栏中,打开“构建 phases”面板。
- 展开“Link Binary with Libraries”组,并添加 SwiftClient.framework。
- 在项目文件中
import SwiftClient
并开始使用 SwiftClient。
使用方法
基本示例
var client = Client()
.baseUrl("http://myapi.org")
.onError({e in alertError(e)});
// GET http://myapi.org/get?key=value&key2=value2
client.get("/get")
.query(["key": "value", "key2": "value2"])
.set("header", "headerValue")
.end({(res:Response) -> Void in
if(res.basicStatus == .OK) { // status of 2xx
handleResponseJson(res.body)
}
else {
handleErrorJson(res.body)
}
})
客户端
客户端就像是请求工厂。客户端对象使用函数创建请求对象。
client.get(url)
client.post(url)
client.put(url)
client.patch(url)
client.delete(url)
client.head(url)
中间件
中间件可以用作插件,影响客户端创建的每个请求。
Client().use({(req:Request) -> Request in
// perform actions on the request.
})
基本URL
为任何以“/”开始的URL请求设置基本URL。
var client = Client().baseUrl("http://myapi.org");
client.get("/endpoint").end(...);
响应转换器
添加一个影响从客户端请求中检索到的每个响应的函数。
Client().transform({(res:Response) -> Response in
// perform actions on the response
})
错误处理器
为客户端作出的任何请求添加默认错误处理器。
Client().onError({(err:NSError) -> Void in
// handle error
})
请求
设置头信息
可以通过传递键和值或字符串到字符串的字典来在请求上设置头信息。
Client().get(url).set(key, value)
Client().get(url).set([key : value, key2: value2])
中间件
中间件可以用作插件,影响请求。
Client().get(url).use({(req:Request) -> Request in
// perform actions on the request.
})
响应转换器
添加一个影响从请求中检索到的响应的功能。
Client().get(url).transform({(res:Response) -> Response in
// perform actions on the response
})
设置内容类型
可以使用缩写名称(如json, html, form, urlencoded, form-data, xml)或完整类型(例如,application/json)来设置内容类型。
Client().get(url).type("json")
查询参数
可以通过传递键值或字符串到字符串的字典来将查询参数添加到URL中。
Client().get(url).query(key, value)
Client().get(url).query([key : value, key2: value2])
请求体
可以在请求体中发送数据。如果内容类型设置为“form”或“json”,则请求会尝试格式化数据并发送它。传递的字典默认类型为JSON。
Client().post(url).type("json").send([1,2,3,4]);
Client().post(url).send([key : value, key2 : value2]);
Client().post(url).type("form").send([key : value, key2 : value2]);
Client().post(url).type("html").send("<html>").send("</html>");
基本访问认证
为请求执行基本HTTP认证。
Client().get(url).auth("username", "password");
多部分请求/文件上传
可以使用字段和附件来创建多部分请求。此类型的请求会自动设置内容类型。如果附加了一个不存在的路径,则附件的内容将为空。
这些函数与向请求体添加数据的其他函数不兼容。
// Adds a field to the multipart data
Client().post(url).field("key", "value")
// Attaches a file to field fileKey, with data content, and a filename of filename.ext (and an inferred MIMEType).
Client().post(url).attach("fileKey", NSData(contentsOfFile: filePath), "filename.ext")
// Attaches a file to field imageKey, with data content, a filename of image.png, and an explicit MIMEType of image/png
Client().post(url).attach("imageKey", NSData(contentsOfFile: "image.png"), "image.png", withMimeType: "image/png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is image.png, and the MIMEType is inferred.
Client().post(url).attach("imageKey", "/path/to/image.png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is formImage.png, and the MIMEType is inferred.
Client().post(url).attach("imageKey", "/path/to/image.png", "formImage.png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is formImage.png, and the MIMEType is explicitly set to image/png.
Client().post(url).attach("imageKey", "/path/to/image.png", "formImage.png", withMimeType: "image/png")
MIMEType参数是可选的。如果没有提供,SwiftClient会尝试从文件扩展名推断它。
请求超时时间
设置请求的超时时间。
Client().get(url).timeout(timeoutInSeconds);
NSURLSessionDelegate
设置底层的NSURLSessionDelegate。
Client().get(url).delegate(delegate);
处理请求错误
为一个请求添加错误处理器。
Client().get(url).onError({(err:NSError) -> Void in
// handle error
})
执行请求
通过传入响应处理器和可选的错误处理器来执行并处理请求。
Client().get(url).end(responseHandler);
Client().get(url).end(responseHandler, onError: errorHandler); // Overrides all other error handlers.
响应
字段
response.status
- HTTP响应状态代码(Response.ResponseType)。
response.text
- 可选的包含响应正文文本的字符串。
response.data
- 可选的包含响应原始正文数据的NSData对象。
response.body
- 可选对象,包含对响应体的解析版本(适用于JSON和表单响应)。
response.headers
- 包含响应头部的字符串到字符串的字典。
ResponseType
ResponseType是一个新的枚举类型,引入到客户端中。我们不再需要无数分配内存的布尔值,而是使用枚举类型。跟以前一样,您可以检查所有之前使用的HTTP状态码。
BasicResponseType
基于statusType的枚举类型。