JSONRequest 0.4.0

JSONRequest 0.4.0

测试已测试
Lang语言 SwiftSwift
许可 MIT
发布最新发布2016年3月
SPM支持 SPM

Eneko Alonso 维护。



  • 作者:
  • Eneko Alonso

JSONRequest

JSONRequest 是一个小巧的 Swift 库,用于执行 HTTP JSON 请求。

JSONRequest 提供了一个简洁且易于使用的 API,用于异步和同步地提交 HTTP 请求(参见为什么同步?你疯了吗?)。

同步使用

同步 GET

let result = JSONRequest.get("http://httpbin.org/get?hello=world")
if let value = result.data?["args"]??["hello"] as? String {
    print(value) // Outputs "world"
}

同步 POST

let postResult = JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"])
if let value = postResult.data?["json"]??["hello"] as? String {
    print(value) // Outputs "world"
}

异步使用

异步 GET

JSONRequest.get("http://httpbin.org/get?hello=world") { result in
    if let value = result.data?["args"]??["hello"] as? String {
        print(value) // Outputs "world"
    }
}

异步 POST

JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"]) { result in
    if let value = result.data?["json"]??["hello"] as? String {
        print(value) // Outputs "world"
    }
}

向服务器发送数据

查询参数

URL 参数可以作为 [String: AnyObject] 字典传递,并会自动进行 URL 编码并附加到 URL 字符串上。所有请求都允许查询参数,无论使用的 HTTP 方法是什么。查询参数字典的值在 URL 编码之前将转换为 String

JSON 负载

响应会自动解析(预期为有效的 JSON 响应),并以 AnyObject 格式返回(有效的 JSON 值包括 ArrayDictionaryIntDoubleStringnil

自定义头

所有 JSONRequest 请求都会自动包含以下默认头:

Content-Type: application/json
Accept: application/json

可以通过 urlRequest 属性访问底层的 NSMutableURLRequest 对象。

为什么要同步?你疯了吗?

iOS 应用中的使用

命令行应用程序中的使用

游乐场中的使用