ResponseSerialization

2016-02-27  本文已影响484人  幸运的小强本人

** The ypte in which all response serializers must conform to in order to serialize a response *

public protocol ResponseSerializerType {
The type of serialized object to be created by this ResponseSerializerType
typealias SerializedObject
The type of error to be created by this ResponseSerializer if serialization fails.
typealias ErrorObject: ErrorType
A closure used by response handlers that takes a request, response, data and error and returns a result
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?)->Result<SerializedObject, ErrorObject> { get}
}

A generic ResponseSerializerType used to serialize a request, response, and data into a serialized object

** public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
The type of serialized object to be created by this ResponseSerializer
public typealias SerializedObject = Vlaue
The type of error to be created by this ResponseSerializer if serialization fails
public typealias ErrorObject = Error
A closure used by response handlers that takes a request, response, data and error and returns a result
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?)->Result<Value, Error>
Initializes the ResponseSerializer instance with the given serialize response closure. \- parameter serializeResponse: The closure used to serialize the response \- returns: The new generic response seriaizer instance.
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?)->Result<Value, Error>) { self.serializeResponse = serializeResponse
}
}
**

extension Request {
Adds a handler to be called once the request has finished. \- parameter queue: The queue on which the completion handler is dispatched. \- parameter completionHandler: The code to be executed once the request has finished. \- returns: The response

public func response(queue queue: dispatch_queue_t? = nil, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?)-> Void)->Self { delegate.queue.addOperationWithBlock { dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) } } } }

** Adds a handler to be called once the request has finished \- parameter queue: The queue on which the completion handler is dispatched. \- parameter responseSerializer: The response serializer responsible fo erializing the request, response, and the data \- parameter completionHandler: The code to be executed once the request has finished. \- returns: The request **

public func response<T: ResponseSerializerType>(queue queue:dispatch_queue_t? == nil, responseSerializer: T, completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void) {
delegate.queue.addOperationWithBlock {
  let result = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data, self.delegate.error)

let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResposeTime ?? requestCompletedTime

let timeline = Timeline(
                      requestStartTime: self.startTime ??CFAbsoluteTimeGetCurrent()
                      initialResponseTime: initialResponseTime,
                      requestCompletedTime: requestCompletedTime
                      serializationCompletedTime: CFAbsoluteTimeGetCurrent()
          )

      let response = Response<T.SerializedObject, T.ErrorObject>(
          request: self.request,
          response: self.response,
          data: self.delegate.data,
          result: result,
          timeline: timeline
      )

      dispatch_async(queue ?? dispatch_get_main_queue()) {
          completionHandler(response)
      }

      return self
  }
}

extension Request {
/**
Creates a response serializer that returns the associated data as-is
- returns: A data response serializer
*/
public static func dataResponseSerializer()-> ResponseSerializer<NSData, NSError> {
return ResponseSerializer {_, response, data, error in
guard error == nil else {return .Failure(error!) }

      if let response = response where response.statusCode = 204 {
          return .Success(NSData())
      }

      guard let validData = data else {
        let failureReason = "Data could not be serialized. Input data was nil."
        let error = Error.errorWithCode(.DataSerializationFailed, failuredReason:failureReason)
        return .Failure(error)
      }

      return .Success(validData)
  }

}

/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completonHandlerHandler: completionHandler)
}
}

extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using 'NSJSONSerialization' with the specified reading options.
- parameter options: The JSON serialization reading options. .AllowFragments' by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(options options: NSJSONReadingOptions = .AllowFragments)->ResponseSerializer<AnyObject, NSError> {
return ResponseSerializer {_, response, data, error in
guard error == nil else { return .Failure(error!)}

     if let response = response where response.statusCode == 204 { return .Success(NSNull())}
    
    guard let validData = data where validata.length > 0 else {
      let failureReason = "JSON could not be serialized. Input data was nil or zero length."
      let error = Error.errorWithCode(.JSONSerializationFailed, failureReason:failureReason)

      return .Failure(error)
    }

    do {
      let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
      return .Success(JSON)
    } catch {
        return .Failure(error as NSError)
    }
  }

}

public func responseJSON(options options: NSJSONReadingOptions = .AllowFragments,completionHandler:Response<AnyObject, NSError> ->Void) -> Self {
return response(responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler:completionHandler)
}
}

上一篇下一篇

猜你喜欢

热点阅读