Alamofire-Response

Response 提供了网络请求数据完成后的回调功能,包含

  • 默认数据直接回调
  • 提供默认json解析、propertyList解析、data解析、string解析回调
  • 自定义解析后回调

默认数据回调DefaultDataResponse

public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
        delegate.queue.addOperation {
            (queue ?? DispatchQueue.main).async {
                var dataResponse = DefaultDataResponse(
                    request: self.request,
                    response: self.response,
                    data: self.delegate.data,
                    error: self.delegate.error,
                    timeline: self.timeline
                )
                dataResponse.add(self.delegate.metrics)
                completionHandler(dataResponse)
            }
        }
        return self
    }

DefaultDataResponse保存了HTTPURLResponsedata等信息,直接回调返回结构体对象

JSON解析

 public func responseJSON(
        queue: DispatchQueue? = nil,
        options: JSONSerialization.ReadingOptions = .allowFragments,
        completionHandler: @escaping (DataResponse) -> Void)
        -> Self
    {
        return response(
            queue: queue,
            responseSerializer: DataRequest.jsonResponseSerializer(options: options),
            completionHandler: completionHandler
        )
    }

JSON序列化数据

do {
            let json = try JSONSerialization.jsonObject(with: validData, options: options)
            return .success(json)
        } catch {
            return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
        }

自定义解析

.response(responseSerializer: DataResponseSerializer(serializeResponse: { (urlRequest, response, data, error) -> Result in
                print("原始数据:\(response)")
                return .success("返回一个自定义解析后成功的数据")
            })) { (response) in
                print(response)
        }

执行自定义闭包,返回result对象,最后回调DataResponse对象

delegate.queue.addOperation {
            let result = responseSerializer.serializeResponse(
                self.request,
                self.response,
                self.delegate.data,
                self.delegate.error
            )

            var dataResponse = DataResponse(
                request: self.request,
                response: self.response,
                data: self.delegate.data,
                result: result,
                timeline: self.timeline
            )

            dataResponse.add(self.delegate.metrics)

            (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }

你可能感兴趣的:(Alamofire-Response)