ResponseSerialization.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. //
  2. // ResponseSerialization.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// The type in which all data response serializers must conform to in order to serialize a response.
  26. public protocol DataResponseSerializerProtocol {
  27. /// The type of serialized object to be created by this `DataResponseSerializerType`.
  28. associatedtype SerializedObject
  29. /// A closure used by response handlers that takes a request, response, data and error and returns a result.
  30. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get }
  31. }
  32. // MARK: -
  33. /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object.
  34. public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol {
  35. /// The type of serialized object to be created by this `DataResponseSerializer`.
  36. public typealias SerializedObject = Value
  37. /// A closure used by response handlers that takes a request, response, data and error and returns a result.
  38. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>
  39. /// Initializes the `ResponseSerializer` instance with the given serialize response closure.
  40. ///
  41. /// - parameter serializeResponse: The closure used to serialize the response.
  42. ///
  43. /// - returns: The new generic response serializer instance.
  44. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
  45. self.serializeResponse = serializeResponse
  46. }
  47. }
  48. // MARK: -
  49. /// The type in which all download response serializers must conform to in order to serialize a response.
  50. public protocol DownloadResponseSerializerProtocol {
  51. /// The type of serialized object to be created by this `DownloadResponseSerializerType`.
  52. associatedtype SerializedObject
  53. /// A closure used by response handlers that takes a request, response, url and error and returns a result.
  54. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get }
  55. }
  56. // MARK: -
  57. /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object.
  58. public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol {
  59. /// The type of serialized object to be created by this `DownloadResponseSerializer`.
  60. public typealias SerializedObject = Value
  61. /// A closure used by response handlers that takes a request, response, url and error and returns a result.
  62. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>
  63. /// Initializes the `ResponseSerializer` instance with the given serialize response closure.
  64. ///
  65. /// - parameter serializeResponse: The closure used to serialize the response.
  66. ///
  67. /// - returns: The new generic response serializer instance.
  68. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) {
  69. self.serializeResponse = serializeResponse
  70. }
  71. }
  72. // MARK: - Timeline
  73. extension Request {
  74. var timeline: Timeline {
  75. let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  76. let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  77. return Timeline(
  78. requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
  79. initialResponseTime: initialResponseTime,
  80. requestCompletedTime: requestCompletedTime,
  81. serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  82. )
  83. }
  84. }
  85. // MARK: - Default
  86. extension DataRequest {
  87. /// Adds a handler to be called once the request has finished.
  88. ///
  89. /// - parameter queue: The queue on which the completion handler is dispatched.
  90. /// - parameter completionHandler: The code to be executed once the request has finished.
  91. ///
  92. /// - returns: The request.
  93. @discardableResult
  94. public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
  95. delegate.queue.addOperation {
  96. (queue ?? DispatchQueue.main).async {
  97. var dataResponse = DefaultDataResponse(
  98. request: self.request,
  99. response: self.response,
  100. data: self.delegate.data,
  101. error: self.delegate.error,
  102. timeline: self.timeline
  103. )
  104. dataResponse.add(self.delegate.metrics)
  105. completionHandler(dataResponse)
  106. }
  107. }
  108. return self
  109. }
  110. /// Adds a handler to be called once the request has finished.
  111. ///
  112. /// - parameter queue: The queue on which the completion handler is dispatched.
  113. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  114. /// and data.
  115. /// - parameter completionHandler: The code to be executed once the request has finished.
  116. ///
  117. /// - returns: The request.
  118. @discardableResult
  119. public func response<T: DataResponseSerializerProtocol>(
  120. queue: DispatchQueue? = nil,
  121. responseSerializer: T,
  122. completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
  123. -> Self
  124. {
  125. delegate.queue.addOperation {
  126. let result = responseSerializer.serializeResponse(
  127. self.request,
  128. self.response,
  129. self.delegate.data,
  130. self.delegate.error
  131. )
  132. var dataResponse = DataResponse<T.SerializedObject>(
  133. request: self.request,
  134. response: self.response,
  135. data: self.delegate.data,
  136. result: result,
  137. timeline: self.timeline
  138. )
  139. dataResponse.add(self.delegate.metrics)
  140. (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
  141. }
  142. return self
  143. }
  144. }
  145. extension DownloadRequest {
  146. /// Adds a handler to be called once the request has finished.
  147. ///
  148. /// - parameter queue: The queue on which the completion handler is dispatched.
  149. /// - parameter completionHandler: The code to be executed once the request has finished.
  150. ///
  151. /// - returns: The request.
  152. @discardableResult
  153. public func response(
  154. queue: DispatchQueue? = nil,
  155. completionHandler: @escaping (DefaultDownloadResponse) -> Void)
  156. -> Self
  157. {
  158. delegate.queue.addOperation {
  159. (queue ?? DispatchQueue.main).async {
  160. var downloadResponse = DefaultDownloadResponse(
  161. request: self.request,
  162. response: self.response,
  163. temporaryURL: self.downloadDelegate.temporaryURL,
  164. destinationURL: self.downloadDelegate.destinationURL,
  165. resumeData: self.downloadDelegate.resumeData,
  166. error: self.downloadDelegate.error,
  167. timeline: self.timeline
  168. )
  169. downloadResponse.add(self.delegate.metrics)
  170. completionHandler(downloadResponse)
  171. }
  172. }
  173. return self
  174. }
  175. /// Adds a handler to be called once the request has finished.
  176. ///
  177. /// - parameter queue: The queue on which the completion handler is dispatched.
  178. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  179. /// and data contained in the destination url.
  180. /// - parameter completionHandler: The code to be executed once the request has finished.
  181. ///
  182. /// - returns: The request.
  183. @discardableResult
  184. public func response<T: DownloadResponseSerializerProtocol>(
  185. queue: DispatchQueue? = nil,
  186. responseSerializer: T,
  187. completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
  188. -> Self
  189. {
  190. delegate.queue.addOperation {
  191. let result = responseSerializer.serializeResponse(
  192. self.request,
  193. self.response,
  194. self.downloadDelegate.fileURL,
  195. self.downloadDelegate.error
  196. )
  197. var downloadResponse = DownloadResponse<T.SerializedObject>(
  198. request: self.request,
  199. response: self.response,
  200. temporaryURL: self.downloadDelegate.temporaryURL,
  201. destinationURL: self.downloadDelegate.destinationURL,
  202. resumeData: self.downloadDelegate.resumeData,
  203. result: result,
  204. timeline: self.timeline
  205. )
  206. downloadResponse.add(self.delegate.metrics)
  207. (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) }
  208. }
  209. return self
  210. }
  211. }
  212. // MARK: - Data
  213. extension Request {
  214. /// Returns a result data type that contains the response data as-is.
  215. ///
  216. /// - parameter response: The response from the server.
  217. /// - parameter data: The data returned from the server.
  218. /// - parameter error: The error already encountered if it exists.
  219. ///
  220. /// - returns: The result data type.
  221. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
  222. guard error == nil else { return .failure(error!) }
  223. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }
  224. guard let validData = data else {
  225. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  226. }
  227. return .success(validData)
  228. }
  229. }
  230. extension DataRequest {
  231. /// Creates a response serializer that returns the associated data as-is.
  232. ///
  233. /// - returns: A data response serializer.
  234. public static func dataResponseSerializer() -> DataResponseSerializer<Data> {
  235. return DataResponseSerializer { _, response, data, error in
  236. return Request.serializeResponseData(response: response, data: data, error: error)
  237. }
  238. }
  239. /// Adds a handler to be called once the request has finished.
  240. ///
  241. /// - parameter completionHandler: The code to be executed once the request has finished.
  242. ///
  243. /// - returns: The request.
  244. @discardableResult
  245. public func responseData(
  246. queue: DispatchQueue? = nil,
  247. completionHandler: @escaping (DataResponse<Data>) -> Void)
  248. -> Self
  249. {
  250. return response(
  251. queue: queue,
  252. responseSerializer: DataRequest.dataResponseSerializer(),
  253. completionHandler: completionHandler
  254. )
  255. }
  256. }
  257. extension DownloadRequest {
  258. /// Creates a response serializer that returns the associated data as-is.
  259. ///
  260. /// - returns: A data response serializer.
  261. public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> {
  262. return DownloadResponseSerializer { _, response, fileURL, error in
  263. guard error == nil else { return .failure(error!) }
  264. guard let fileURL = fileURL else {
  265. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  266. }
  267. do {
  268. let data = try Data(contentsOf: fileURL)
  269. return Request.serializeResponseData(response: response, data: data, error: error)
  270. } catch {
  271. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  272. }
  273. }
  274. }
  275. /// Adds a handler to be called once the request has finished.
  276. ///
  277. /// - parameter completionHandler: The code to be executed once the request has finished.
  278. ///
  279. /// - returns: The request.
  280. @discardableResult
  281. public func responseData(
  282. queue: DispatchQueue? = nil,
  283. completionHandler: @escaping (DownloadResponse<Data>) -> Void)
  284. -> Self
  285. {
  286. return response(
  287. queue: queue,
  288. responseSerializer: DownloadRequest.dataResponseSerializer(),
  289. completionHandler: completionHandler
  290. )
  291. }
  292. }
  293. // MARK: - String
  294. extension Request {
  295. /// Returns a result string type initialized from the response data with the specified string encoding.
  296. ///
  297. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  298. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  299. /// - parameter response: The response from the server.
  300. /// - parameter data: The data returned from the server.
  301. /// - parameter error: The error already encountered if it exists.
  302. ///
  303. /// - returns: The result data type.
  304. public static func serializeResponseString(
  305. encoding: String.Encoding?,
  306. response: HTTPURLResponse?,
  307. data: Data?,
  308. error: Error?)
  309. -> Result<String>
  310. {
  311. guard error == nil else { return .failure(error!) }
  312. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") }
  313. guard let validData = data else {
  314. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  315. }
  316. var convertedEncoding = encoding
  317. if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil {
  318. convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
  319. CFStringConvertIANACharSetNameToEncoding(encodingName))
  320. )
  321. }
  322. let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
  323. if let string = String(data: validData, encoding: actualEncoding) {
  324. return .success(string)
  325. } else {
  326. return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
  327. }
  328. }
  329. }
  330. extension DataRequest {
  331. /// Creates a response serializer that returns a result string type initialized from the response data with
  332. /// the specified string encoding.
  333. ///
  334. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  335. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  336. ///
  337. /// - returns: A string response serializer.
  338. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
  339. return DataResponseSerializer { _, response, data, error in
  340. return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
  341. }
  342. }
  343. /// Adds a handler to be called once the request has finished.
  344. ///
  345. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  346. /// server response, falling back to the default HTTP default character set,
  347. /// ISO-8859-1.
  348. /// - parameter completionHandler: A closure to be executed once the request has finished.
  349. ///
  350. /// - returns: The request.
  351. @discardableResult
  352. public func responseString(
  353. queue: DispatchQueue? = nil,
  354. encoding: String.Encoding? = nil,
  355. completionHandler: @escaping (DataResponse<String>) -> Void)
  356. -> Self
  357. {
  358. return response(
  359. queue: queue,
  360. responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
  361. completionHandler: completionHandler
  362. )
  363. }
  364. }
  365. extension DownloadRequest {
  366. /// Creates a response serializer that returns a result string type initialized from the response data with
  367. /// the specified string encoding.
  368. ///
  369. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  370. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  371. ///
  372. /// - returns: A string response serializer.
  373. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> {
  374. return DownloadResponseSerializer { _, response, fileURL, error in
  375. guard error == nil else { return .failure(error!) }
  376. guard let fileURL = fileURL else {
  377. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  378. }
  379. do {
  380. let data = try Data(contentsOf: fileURL)
  381. return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
  382. } catch {
  383. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  384. }
  385. }
  386. }
  387. /// Adds a handler to be called once the request has finished.
  388. ///
  389. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  390. /// server response, falling back to the default HTTP default character set,
  391. /// ISO-8859-1.
  392. /// - parameter completionHandler: A closure to be executed once the request has finished.
  393. ///
  394. /// - returns: The request.
  395. @discardableResult
  396. public func responseString(
  397. queue: DispatchQueue? = nil,
  398. encoding: String.Encoding? = nil,
  399. completionHandler: @escaping (DownloadResponse<String>) -> Void)
  400. -> Self
  401. {
  402. return response(
  403. queue: queue,
  404. responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding),
  405. completionHandler: completionHandler
  406. )
  407. }
  408. }
  409. // MARK: - JSON
  410. extension Request {
  411. /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
  412. /// with the specified reading options.
  413. ///
  414. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  415. /// - parameter response: The response from the server.
  416. /// - parameter data: The data returned from the server.
  417. /// - parameter error: The error already encountered if it exists.
  418. ///
  419. /// - returns: The result data type.
  420. public static func serializeResponseJSON(
  421. options: JSONSerialization.ReadingOptions,
  422. response: HTTPURLResponse?,
  423. data: Data?,
  424. error: Error?)
  425. -> Result<Any>
  426. {
  427. guard error == nil else { return .failure(error!) }
  428. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
  429. guard let validData = data, validData.count > 0 else {
  430. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  431. }
  432. do {
  433. let json = try JSONSerialization.jsonObject(with: validData, options: options)
  434. return .success(json)
  435. } catch {
  436. return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
  437. }
  438. }
  439. }
  440. extension DataRequest {
  441. /// Creates a response serializer that returns a JSON object result type constructed from the response data using
  442. /// `JSONSerialization` with the specified reading options.
  443. ///
  444. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  445. ///
  446. /// - returns: A JSON object response serializer.
  447. public static func jsonResponseSerializer(
  448. options: JSONSerialization.ReadingOptions = .allowFragments)
  449. -> DataResponseSerializer<Any>
  450. {
  451. return DataResponseSerializer { _, response, data, error in
  452. return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
  453. }
  454. }
  455. /// Adds a handler to be called once the request has finished.
  456. ///
  457. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  458. /// - parameter completionHandler: A closure to be executed once the request has finished.
  459. ///
  460. /// - returns: The request.
  461. @discardableResult
  462. public func responseJSON(
  463. queue: DispatchQueue? = nil,
  464. options: JSONSerialization.ReadingOptions = .allowFragments,
  465. completionHandler: @escaping (DataResponse<Any>) -> Void)
  466. -> Self
  467. {
  468. return response(
  469. queue: queue,
  470. responseSerializer: DataRequest.jsonResponseSerializer(options: options),
  471. completionHandler: completionHandler
  472. )
  473. }
  474. }
  475. extension DownloadRequest {
  476. /// Creates a response serializer that returns a JSON object result type constructed from the response data using
  477. /// `JSONSerialization` with the specified reading options.
  478. ///
  479. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  480. ///
  481. /// - returns: A JSON object response serializer.
  482. public static func jsonResponseSerializer(
  483. options: JSONSerialization.ReadingOptions = .allowFragments)
  484. -> DownloadResponseSerializer<Any>
  485. {
  486. return DownloadResponseSerializer { _, response, fileURL, error in
  487. guard error == nil else { return .failure(error!) }
  488. guard let fileURL = fileURL else {
  489. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  490. }
  491. do {
  492. let data = try Data(contentsOf: fileURL)
  493. return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
  494. } catch {
  495. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  496. }
  497. }
  498. }
  499. /// Adds a handler to be called once the request has finished.
  500. ///
  501. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  502. /// - parameter completionHandler: A closure to be executed once the request has finished.
  503. ///
  504. /// - returns: The request.
  505. @discardableResult
  506. public func responseJSON(
  507. queue: DispatchQueue? = nil,
  508. options: JSONSerialization.ReadingOptions = .allowFragments,
  509. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  510. -> Self
  511. {
  512. return response(
  513. queue: queue,
  514. responseSerializer: DownloadRequest.jsonResponseSerializer(options: options),
  515. completionHandler: completionHandler
  516. )
  517. }
  518. }
  519. // MARK: - Property List
  520. extension Request {
  521. /// Returns a plist object contained in a result type constructed from the response data using
  522. /// `PropertyListSerialization` with the specified reading options.
  523. ///
  524. /// - parameter options: The property list reading options. Defaults to `[]`.
  525. /// - parameter response: The response from the server.
  526. /// - parameter data: The data returned from the server.
  527. /// - parameter error: The error already encountered if it exists.
  528. ///
  529. /// - returns: The result data type.
  530. public static func serializeResponsePropertyList(
  531. options: PropertyListSerialization.ReadOptions,
  532. response: HTTPURLResponse?,
  533. data: Data?,
  534. error: Error?)
  535. -> Result<Any>
  536. {
  537. guard error == nil else { return .failure(error!) }
  538. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
  539. guard let validData = data, validData.count > 0 else {
  540. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  541. }
  542. do {
  543. let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
  544. return .success(plist)
  545. } catch {
  546. return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
  547. }
  548. }
  549. }
  550. extension DataRequest {
  551. /// Creates a response serializer that returns an object constructed from the response data using
  552. /// `PropertyListSerialization` with the specified reading options.
  553. ///
  554. /// - parameter options: The property list reading options. Defaults to `[]`.
  555. ///
  556. /// - returns: A property list object response serializer.
  557. public static func propertyListResponseSerializer(
  558. options: PropertyListSerialization.ReadOptions = [])
  559. -> DataResponseSerializer<Any>
  560. {
  561. return DataResponseSerializer { _, response, data, error in
  562. return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
  563. }
  564. }
  565. /// Adds a handler to be called once the request has finished.
  566. ///
  567. /// - parameter options: The property list reading options. Defaults to `[]`.
  568. /// - parameter completionHandler: A closure to be executed once the request has finished.
  569. ///
  570. /// - returns: The request.
  571. @discardableResult
  572. public func responsePropertyList(
  573. queue: DispatchQueue? = nil,
  574. options: PropertyListSerialization.ReadOptions = [],
  575. completionHandler: @escaping (DataResponse<Any>) -> Void)
  576. -> Self
  577. {
  578. return response(
  579. queue: queue,
  580. responseSerializer: DataRequest.propertyListResponseSerializer(options: options),
  581. completionHandler: completionHandler
  582. )
  583. }
  584. }
  585. extension DownloadRequest {
  586. /// Creates a response serializer that returns an object constructed from the response data using
  587. /// `PropertyListSerialization` with the specified reading options.
  588. ///
  589. /// - parameter options: The property list reading options. Defaults to `[]`.
  590. ///
  591. /// - returns: A property list object response serializer.
  592. public static func propertyListResponseSerializer(
  593. options: PropertyListSerialization.ReadOptions = [])
  594. -> DownloadResponseSerializer<Any>
  595. {
  596. return DownloadResponseSerializer { _, response, fileURL, error in
  597. guard error == nil else { return .failure(error!) }
  598. guard let fileURL = fileURL else {
  599. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  600. }
  601. do {
  602. let data = try Data(contentsOf: fileURL)
  603. return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
  604. } catch {
  605. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  606. }
  607. }
  608. }
  609. /// Adds a handler to be called once the request has finished.
  610. ///
  611. /// - parameter options: The property list reading options. Defaults to `[]`.
  612. /// - parameter completionHandler: A closure to be executed once the request has finished.
  613. ///
  614. /// - returns: The request.
  615. @discardableResult
  616. public func responsePropertyList(
  617. queue: DispatchQueue? = nil,
  618. options: PropertyListSerialization.ReadOptions = [],
  619. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  620. -> Self
  621. {
  622. return response(
  623. queue: queue,
  624. responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options),
  625. completionHandler: completionHandler
  626. )
  627. }
  628. }
  629. /// A set of HTTP response status code that do not contain response data.
  630. private let emptyDataStatusCodes: Set<Int> = [204, 205]