TOP

【iOS开发】Alamofire框架的使用二 高级用法(六)
2019-09-03 02:41:08 】 浏览:571
Tags:iOS 开发 Alamofire 框架 使用 高级 用法

or: Error) case objectSerialization(reason: String) }

创建一个自定义的响应序列化器

Alamofire为strings、JSON和Property List提供了内置的响应序列化,但是我们可以通过扩展Alamofire.DataRequest或者Alamofire.DownloadRequest来添加其他序列化。

例如,下面这个例子是一个使用Ono (一个实用的处理iOS和macOS平台的XML和HTML的方式)的响应handler的实现:

extension DataRequest {
    static func xmlResponseSerializer() -> DataResponseSerializer<ONOXMLDocument> { return DataResponseSerializer { request, response, data, error in // 把任何底层的URLSession error传递给 .network case guard error == nil else { return .failure(BackendError.network(error: error!)) } // 使用Alamofire已有的数据序列化器来提取数据,error为nil,因为上一行代码已经把不是nil的error过滤了 let result = Request.serializeResponseData(response: response, data: data, error: nil) guard case let .success(validData) = result else { return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) } do { let xml = try ONOXMLDocument(data: validData) return .success(xml) } catch { return .failure(BackendError.xmlSerialization(error: error)) } } } @discardableResult func responseXMLDocument( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<ONOXMLDocument>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.xmlResponseSerializer(), completionHandler: completionHandler ) } } 

泛型响应对象序列化

泛型可以用来提供自动的、类型安全的响应对象序列化。

protocol ResponseObjectSerializable {
    init?(response: HTTPURLResponse, representation: Any)
}

extension DataRequest {
    func responseObject<T: ResponseObjectSerializable>(
        queue: DispatchQueue? = nil,
        completionHandler: @escaping (DataResponse<T>) -> Void)
        -> Self
    {
        let responseSerializer = DataResponseSerializer<T> { request, response, data, error in guard error == nil else { return .failure(BackendError.network(error: error!)) } let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) guard case let .success(jsonObject) = result else { return .failure(BackendError.jsonSerialization(error: result.error!)) } guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) } return .success(responseObject) } return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) } } 
struct User: ResponseObjectSerializable, CustomStringConvertible {
    let username: String let name: String var description: String { return "User: { username: \(username), name: \(name) }" } init?(response: HTTPURLResponse, representation: Any) { guard let username = response.url?.lastPathComponent, let representation = representation as? [String: Any], let name = representation["name"] as? String else { return nil } self.username = username self.name = name } } 
Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse<User>) in debugPrint(response) if let user = response.result.value { print("User: { username: \(user.username), name: \(user.name) }") } } 

同样地方法可以用来处理返回对象集合的接口:

protocol ResponseCollectionSerializable {
    static func col  
		

请关注公众号获取更多资料


【iOS开发】Alamofire框架的使用二 高级用法(六) https://www.cppentry.com/bencandy.php?fid=89&id=246437

首页 上一页 3 4 5 6 7 8 9 下一页 尾页 6/9/9
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇黑马基础阶段测试题:创建Phone(.. 下一篇Swift4 枚举,例子代码

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: