Swift 4.0中的简单类型化JSON HTTP网络
GET
GET<Dict>("http://httpbin.org/ip").execute(success: { (response) in
let ip: Dict = response
})
let postID = "1"
GET<Dict>("http://jsonplaceholder.typicode.com/posts/#").execute(postID, success: { (response) in
let post: Dict = response
})
POST
let userComment = ["justin": "wow this is cool"]
let endpoint = POST<[String: AnyObject]>("https://api.bridge.com/comments")
endpoint.execute(params: userComment, success: { (commentResponse: [String: AnyObject]) -> () in
// Handle success
}, failure: { (error, data, request, response) in
// Handle failure
})
拦截器
Bridge 的力量在于它可以让你创建自定义的“拦截器”,在请求发送到互联网之前或返回调用者的成功块之前拦截和处理器响应。
根据端点附加自定义头,编写重试处理,编写认证处理器,使用方法隧道。拦截器使 Bridge 能够根据你的项目需求进行极大扩展。
/**
* Conform to the `ResponseInterceptor` protocol for any Bridge that
* needs to work with or alter a request before it's sent over the wire
*/
public protocol ResponseInterceptor {
func process<ReturnType>(endpoint: Endpoint<ReturnType>, inout mutableRequest: NSMutableURLRequest)
}
/**
* Conform to the `ResponseInterceptor` protocol to work with data after
* the request is returned with a response.
*/
public protocol ResponseInterceptor {
func process<ReturnType>(endpoint: Endpoint<ReturnType>, response: NSHTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults
}
示例
对象序列化
Bridge 使用泛型实现,允许你序列化对象,只要你的对象符合 可解析
协议。
public protocol Parseable {
static func parseResponseObject(responseObject: AnyObject) throws -> AnyObject
}
如何实现 可解析
协议完全取决于开发者。你可以手动创建和序列化你的对象
class User: AnyObject, Parseable {
var name: String?
var email: String?
var pictureURL: NSURL?
static func parseResponseObject(responseObject: AnyObject) throws -> AnyObject {
if let dict = responseObject as? Dictionary<String, AnyObject> {
let user = User()
user.name = dict["name"] as? String
user.email = dict["email"] as? String
user.pictureURL = NSURL(string: dict["avatar_url"] as! String)
return user
}
// If parsing encounters an error, throw enum that conforms to ErrorType.
throw BridgeErrorType.Parsing
}
}
或者你可以使用你喜欢的任何序列化库来序列化它们。《这个片段》是在使用 Mantle 模型时的一个现成的解决方案示例,如果你已经在使用 Mantle 模型的话。对 Mantle 模型不需要代码更改。
一旦设置好模型,调用就变得非常简单
let endpoint = GET<GithubUser>("https://api.github.com/users/rawrjustin")
endpoint.execute(success: { (user: GithubUser) in
print(user)
})
let endpoint = GET<Array<GithubUser>>("https://api.github.com/users")
endpoint.execute(success: { (users: Array<GithubUser>) in
print(users)
}, failure: { (error: NSError?) in
print(error)
})
高级功能
基本 URL
你可以设置 Bridge 客户的基 URL
Bridge.sharedInstance.baseURL = "http://api.github.com"
GET<GithubUser>("/users/rawrjustin") // expands to http://api.github.com/users/rawrjustin
通过标记取消
轻松取消任何带有标识符的请求。
Bridge.sharedInstance.cancelWithTag("DebouncedSearch")
可变端点
类似于 Rails 为资源映射 :id,这里使用 ##
作为变量插入路径的字符。
GET
如果在调用 execute() 时传递第一个可变参数 1
,则会映射到 /photos/1
。您可以有多个变量,它们将按顺序分别映射。
附加 HTTP 头部
端点特定拦截器
要求
- iOS 8.0+
- Swift 4.0
安装
pod 'Bridge', '0.4.3'
github "rawrjustin/Bridge"
许可证
Bridge 采用 MIT 许可证。
有问题吗?
打开问题