ResponseSerialization.swift 10.6 KB
Newer Older
1
// ResponseSerialization.swift
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import Foundation

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// MARK: - ResponseSerializer

/**
    The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
    /// The type of serialized object to be created by this `ResponseSerializer`.
    typealias SerializedObject

    /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
    var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
}

/**
    A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
    /// The type of serialized object to be created by this `ResponseSerializer`.
    public typealias SerializedObject = T

    /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
    public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
47 48 49 50

    /**
        Initializes the `GenericResponseSerializer` instance with the given serialize response closure.

51
        - parameter serializeResponse: The closure used to serialize the response.
52

53
        - returns: The new generic response serializer instance.
54 55 56 57
    */
    public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)) {
        self.serializeResponse = serializeResponse
    }
58 59 60
}

// MARK: - Default
61 62

extension Request {
63 64 65 66

    /**
        Adds a handler to be called once the request has finished.

67 68 69
        - parameter queue: The queue on which the completion handler is dispatched.
        - parameter responseSerializer: The response serializer responsible for serializing the request, response, and data.
        - parameter completionHandler: The code to be executed once the request has finished.
70

71
        - returns: The request.
72 73 74 75
    */
    public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
        queue: dispatch_queue_t? = nil,
        responseSerializer: T,
76
        completionHandler: (NSURLRequest?, NSHTTPURLResponse?, V?, NSError?) -> Void)
77 78
        -> Self
    {
79
        delegate.queue.addOperationWithBlock {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            let result: V?
            let error: NSError?

            (result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)

            dispatch_async(queue ?? dispatch_get_main_queue()) {
                completionHandler(self.request, self.response, result, self.delegate.error ?? error)
            }
        }

        return self
    }
}

// MARK: - Data

extension Request {

    /**
        Creates a response serializer that returns the associated data as-is.

101
        - returns: A data response serializer.
102 103 104 105 106 107 108 109 110 111
    */
    public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
        return GenericResponseSerializer { request, response, data in
            return (data, nil)
        }
    }

    /**
        Adds a handler to be called once the request has finished.

112
        - parameter completionHandler: The code to be executed once the request has finished.
113

114
        - returns: The request.
115
    */
116
    public func response(completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
117
        return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
118 119 120 121
    }
}

// MARK: - String
122 123

extension Request {
124

125 126
    /**
        Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
127

128
        - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
129

130
        - returns: A string response serializer.
131
    */
132
    public static func stringResponseSerializer(var encoding encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
133
        return GenericResponseSerializer { _, response, data in
134 135 136
            if data == nil || data?.length == 0 {
                return (nil, nil)
            }
137

138 139
            if let encodingName = response?.textEncodingName where encoding == nil {
                encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
140
            }
141

142
            let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
143

144 145 146
            return (string, nil)
        }
    }
147

148 149
    /**
        Adds a handler to be called once the request has finished.
150

151 152
        - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
        - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
153

154
        - returns: The request.
155
    */
156
    public func responseString(
157 158
        encoding encoding: NSStringEncoding? = nil,
        completionHandler: (NSURLRequest?, NSHTTPURLResponse?, String?, NSError?) -> Void)
159 160 161 162
        -> Self
    {
        return response(
            responseSerializer: Request.stringResponseSerializer(encoding: encoding),
163
            completionHandler: completionHandler
164
        )
165 166 167
    }
}

168
// MARK: - JSON
169 170

extension Request {
171

172 173
    /**
        Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
174

175
        - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
176

177
        - returns: A JSON object response serializer.
178
    */
179
    public static func JSONResponseSerializer(options options: NSJSONReadingOptions = .AllowFragments) -> GenericResponseSerializer<AnyObject> {
180
        return GenericResponseSerializer { request, response, data in
181 182 183
            if data == nil || data?.length == 0 {
                return (nil, nil)
            }
184

185
            var JSON: AnyObject?
186
            var serializationError: NSError?
187 188 189 190

            do {
                JSON = try NSJSONSerialization.JSONObjectWithData(data!, options: options)
            } catch {
191
                serializationError = error as NSError
192
            }
193

194 195 196
            return (JSON, serializationError)
        }
    }
197

198 199
    /**
        Adds a handler to be called once the request has finished.
200

201 202
        - parameter options: The JSON serialization reading options. `.AllowFragments` by default.
        - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
203

204
        - returns: The request.
205
    */
206
    public func responseJSON(
207 208
        options options: NSJSONReadingOptions = .AllowFragments,
        completionHandler: (NSURLRequest?, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
209 210 211 212
        -> Self
    {
        return response(
            responseSerializer: Request.JSONResponseSerializer(options: options),
213
            completionHandler: completionHandler
214
        )
215 216 217
    }
}

218
// MARK: - Property List
219 220

extension Request {
221

222 223
    /**
        Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
224

225
        - parameter options: The property list reading options. `0` by default.
226

227
        - returns: A property list object response serializer.
228
    */
229 230 231 232
    public static func propertyListResponseSerializer(
        options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
        -> GenericResponseSerializer<AnyObject>
    {
233
        return GenericResponseSerializer { request, response, data in
234 235 236
            if data == nil || data?.length == 0 {
                return (nil, nil)
            }
237

238
            var plist: AnyObject?
239
            var propertyListSerializationError: NSError?
240 241 242 243

            do {
                plist = try NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil)
            } catch {
244
                propertyListSerializationError = error as NSError
245
            }
246

247 248 249
            return (plist, propertyListSerializationError)
        }
    }
250

251 252
    /**
        Adds a handler to be called once the request has finished.
253

254 255
        - parameter options: The property list reading options. `0` by default.
        - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
256

257
        - returns: The request.
258
    */
259
    public func responsePropertyList(
260 261
        options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
        completionHandler: (NSURLRequest?, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
262 263 264 265
        -> Self
    {
        return response(
            responseSerializer: Request.propertyListResponseSerializer(options: options),
266
            completionHandler: completionHandler
267
        )
268 269
    }
}