ResponseSerialization.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. //
  2. // ResponseSerialization.swift
  3. //
  4. // Copyright (c) 2014 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 requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent()
  76. let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
  77. let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
  78. return Timeline(
  79. requestStartTime: requestStartTime,
  80. initialResponseTime: initialResponseTime,
  81. requestCompletedTime: requestCompletedTime,
  82. serializationCompletedTime: CFAbsoluteTimeGetCurrent()
  83. )
  84. }
  85. }
  86. // MARK: - Default
  87. extension DataRequest {
  88. /// Adds a handler to be called once the request has finished.
  89. ///
  90. /// - parameter queue: The queue on which the completion handler is dispatched.
  91. /// - parameter completionHandler: The code to be executed once the request has finished.
  92. ///
  93. /// - returns: The request.
  94. @discardableResult
  95. public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
  96. delegate.queue.addOperation {
  97. (queue ?? DispatchQueue.main).async {
  98. var dataResponse = DefaultDataResponse(
  99. request: self.request,
  100. response: self.response,
  101. data: self.delegate.data,
  102. error: self.delegate.error,
  103. timeline: self.timeline
  104. )
  105. dataResponse.add(self.delegate.metrics)
  106. completionHandler(dataResponse)
  107. }
  108. }
  109. return self
  110. }
  111. /// Adds a handler to be called once the request has finished.
  112. ///
  113. /// - parameter queue: The queue on which the completion handler is dispatched.
  114. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  115. /// and data.
  116. /// - parameter completionHandler: The code to be executed once the request has finished.
  117. ///
  118. /// - returns: The request.
  119. @discardableResult
  120. public func response<T: DataResponseSerializerProtocol>(
  121. queue: DispatchQueue? = nil,
  122. responseSerializer: T,
  123. completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
  124. -> Self
  125. {
  126. delegate.queue.addOperation {
  127. let result = responseSerializer.serializeResponse(
  128. self.request,
  129. self.response,
  130. self.delegate.data,
  131. self.delegate.error
  132. )
  133. var dataResponse = DataResponse<T.SerializedObject>(
  134. request: self.request,
  135. response: self.response,
  136. data: self.delegate.data,
  137. result: result,
  138. timeline: self.timeline
  139. )
  140. dataResponse.add(self.delegate.metrics)
  141. (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
  142. }
  143. return self
  144. }
  145. }
  146. extension DownloadRequest {
  147. /// Adds a handler to be called once the request has finished.
  148. ///
  149. /// - parameter queue: The queue on which the completion handler is dispatched.
  150. /// - parameter completionHandler: The code to be executed once the request has finished.
  151. ///
  152. /// - returns: The request.
  153. @discardableResult
  154. public func response(
  155. queue: DispatchQueue? = nil,
  156. completionHandler: @escaping (DefaultDownloadResponse) -> Void)
  157. -> Self
  158. {
  159. delegate.queue.addOperation {
  160. (queue ?? DispatchQueue.main).async {
  161. var downloadResponse = DefaultDownloadResponse(
  162. request: self.request,
  163. response: self.response,
  164. temporaryURL: self.downloadDelegate.temporaryURL,
  165. destinationURL: self.downloadDelegate.destinationURL,
  166. resumeData: self.downloadDelegate.resumeData,
  167. error: self.downloadDelegate.error,
  168. timeline: self.timeline
  169. )
  170. downloadResponse.add(self.delegate.metrics)
  171. completionHandler(downloadResponse)
  172. }
  173. }
  174. return self
  175. }
  176. /// Adds a handler to be called once the request has finished.
  177. ///
  178. /// - parameter queue: The queue on which the completion handler is dispatched.
  179. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
  180. /// and data contained in the destination url.
  181. /// - parameter completionHandler: The code to be executed once the request has finished.
  182. ///
  183. /// - returns: The request.
  184. @discardableResult
  185. public func response<T: DownloadResponseSerializerProtocol>(
  186. queue: DispatchQueue? = nil,
  187. responseSerializer: T,
  188. completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
  189. -> Self
  190. {
  191. delegate.queue.addOperation {
  192. let result = responseSerializer.serializeResponse(
  193. self.request,
  194. self.response,
  195. self.downloadDelegate.fileURL,
  196. self.downloadDelegate.error
  197. )
  198. var downloadResponse = DownloadResponse<T.SerializedObject>(
  199. request: self.request,
  200. response: self.response,
  201. temporaryURL: self.downloadDelegate.temporaryURL,
  202. destinationURL: self.downloadDelegate.destinationURL,
  203. resumeData: self.downloadDelegate.resumeData,
  204. result: result,
  205. timeline: self.timeline
  206. )
  207. downloadResponse.add(self.delegate.metrics)
  208. (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) }
  209. }
  210. return self
  211. }
  212. }
  213. // MARK: - Data
  214. extension Request {
  215. /// Returns a result data type that contains the response data as-is.
  216. ///
  217. /// - parameter response: The response from the server.
  218. /// - parameter data: The data returned from the server.
  219. /// - parameter error: The error already encountered if it exists.
  220. ///
  221. /// - returns: The result data type.
  222. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
  223. guard error == nil else { return .failure(error!) }
  224. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }
  225. guard let validData = data else {
  226. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  227. }
  228. return .success(validData)
  229. }
  230. }
  231. extension DataRequest {
  232. /// Creates a response serializer that returns the associated data as-is.
  233. ///
  234. /// - returns: A data response serializer.
  235. public static func dataResponseSerializer() -> DataResponseSerializer<Data> {
  236. return DataResponseSerializer { _, response, data, error in
  237. return Request.serializeResponseData(response: response, data: data, error: error)
  238. }
  239. }
  240. /// Adds a handler to be called once the request has finished.
  241. ///
  242. /// - parameter completionHandler: The code to be executed once the request has finished.
  243. ///
  244. /// - returns: The request.
  245. @discardableResult
  246. public func responseData(
  247. queue: DispatchQueue? = nil,
  248. completionHandler: @escaping (DataResponse<Data>) -> Void)
  249. -> Self
  250. {
  251. return response(
  252. queue: queue,
  253. responseSerializer: DataRequest.dataResponseSerializer(),
  254. completionHandler: completionHandler
  255. )
  256. }
  257. }
  258. extension DownloadRequest {
  259. /// Creates a response serializer that returns the associated data as-is.
  260. ///
  261. /// - returns: A data response serializer.
  262. public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> {
  263. return DownloadResponseSerializer { _, response, fileURL, error in
  264. guard error == nil else { return .failure(error!) }
  265. guard let fileURL = fileURL else {
  266. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  267. }
  268. do {
  269. let data = try Data(contentsOf: fileURL)
  270. return Request.serializeResponseData(response: response, data: data, error: error)
  271. } catch {
  272. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  273. }
  274. }
  275. }
  276. /// Adds a handler to be called once the request has finished.
  277. ///
  278. /// - parameter completionHandler: The code to be executed once the request has finished.
  279. ///
  280. /// - returns: The request.
  281. @discardableResult
  282. public func responseData(
  283. queue: DispatchQueue? = nil,
  284. completionHandler: @escaping (DownloadResponse<Data>) -> Void)
  285. -> Self
  286. {
  287. return response(
  288. queue: queue,
  289. responseSerializer: DownloadRequest.dataResponseSerializer(),
  290. completionHandler: completionHandler
  291. )
  292. }
  293. }
  294. // MARK: - String
  295. extension Request {
  296. /// Returns a result string type initialized from the response data with the specified string encoding.
  297. ///
  298. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  299. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  300. /// - parameter response: The response from the server.
  301. /// - parameter data: The data returned from the server.
  302. /// - parameter error: The error already encountered if it exists.
  303. ///
  304. /// - returns: The result data type.
  305. public static func serializeResponseString(
  306. encoding: String.Encoding?,
  307. response: HTTPURLResponse?,
  308. data: Data?,
  309. error: Error?)
  310. -> Result<String>
  311. {
  312. guard error == nil else { return .failure(error!) }
  313. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") }
  314. guard let validData = data else {
  315. return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
  316. }
  317. var convertedEncoding = encoding
  318. if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
  319. convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
  320. CFStringConvertIANACharSetNameToEncoding(encodingName))
  321. )
  322. }
  323. let actualEncoding = convertedEncoding ?? .isoLatin1
  324. if let string = String(data: validData, encoding: actualEncoding) {
  325. return .success(string)
  326. } else {
  327. return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
  328. }
  329. }
  330. }
  331. extension DataRequest {
  332. /// Creates a response serializer that returns a result string type initialized from the response data with
  333. /// the specified string encoding.
  334. ///
  335. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  336. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  337. ///
  338. /// - returns: A string response serializer.
  339. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
  340. return DataResponseSerializer { _, response, data, error in
  341. return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
  342. }
  343. }
  344. /// Adds a handler to be called once the request has finished.
  345. ///
  346. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  347. /// server response, falling back to the default HTTP default character set,
  348. /// ISO-8859-1.
  349. /// - parameter completionHandler: A closure to be executed once the request has finished.
  350. ///
  351. /// - returns: The request.
  352. @discardableResult
  353. public func responseString(
  354. queue: DispatchQueue? = nil,
  355. encoding: String.Encoding? = nil,
  356. completionHandler: @escaping (DataResponse<String>) -> Void)
  357. -> Self
  358. {
  359. return response(
  360. queue: queue,
  361. responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
  362. completionHandler: completionHandler
  363. )
  364. }
  365. }
  366. extension DownloadRequest {
  367. /// Creates a response serializer that returns a result string type initialized from the response data with
  368. /// the specified string encoding.
  369. ///
  370. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
  371. /// response, falling back to the default HTTP default character set, ISO-8859-1.
  372. ///
  373. /// - returns: A string response serializer.
  374. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> {
  375. return DownloadResponseSerializer { _, response, fileURL, error in
  376. guard error == nil else { return .failure(error!) }
  377. guard let fileURL = fileURL else {
  378. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  379. }
  380. do {
  381. let data = try Data(contentsOf: fileURL)
  382. return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
  383. } catch {
  384. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  385. }
  386. }
  387. }
  388. /// Adds a handler to be called once the request has finished.
  389. ///
  390. /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
  391. /// server response, falling back to the default HTTP default character set,
  392. /// ISO-8859-1.
  393. /// - parameter completionHandler: A closure to be executed once the request has finished.
  394. ///
  395. /// - returns: The request.
  396. @discardableResult
  397. public func responseString(
  398. queue: DispatchQueue? = nil,
  399. encoding: String.Encoding? = nil,
  400. completionHandler: @escaping (DownloadResponse<String>) -> Void)
  401. -> Self
  402. {
  403. return response(
  404. queue: queue,
  405. responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding),
  406. completionHandler: completionHandler
  407. )
  408. }
  409. }
  410. // MARK: - JSON
  411. extension Request {
  412. /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
  413. /// with the specified reading options.
  414. ///
  415. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  416. /// - parameter response: The response from the server.
  417. /// - parameter data: The data returned from the server.
  418. /// - parameter error: The error already encountered if it exists.
  419. ///
  420. /// - returns: The result data type.
  421. public static func serializeResponseJSON(
  422. options: JSONSerialization.ReadingOptions,
  423. response: HTTPURLResponse?,
  424. data: Data?,
  425. error: Error?)
  426. -> Result<Any>
  427. {
  428. guard error == nil else { return .failure(error!) }
  429. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
  430. guard let validData = data, validData.count > 0 else {
  431. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  432. }
  433. do {
  434. let json = try JSONSerialization.jsonObject(with: validData, options: options)
  435. return .success(json)
  436. } catch {
  437. return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
  438. }
  439. }
  440. }
  441. extension DataRequest {
  442. /// Creates a response serializer that returns a JSON object result type constructed from the response data using
  443. /// `JSONSerialization` with the specified reading options.
  444. ///
  445. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  446. ///
  447. /// - returns: A JSON object response serializer.
  448. public static func jsonResponseSerializer(
  449. options: JSONSerialization.ReadingOptions = .allowFragments)
  450. -> DataResponseSerializer<Any>
  451. {
  452. return DataResponseSerializer { _, response, data, error in
  453. return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
  454. }
  455. }
  456. /// Adds a handler to be called once the request has finished.
  457. ///
  458. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  459. /// - parameter completionHandler: A closure to be executed once the request has finished.
  460. ///
  461. /// - returns: The request.
  462. @discardableResult
  463. public func responseJSON(
  464. queue: DispatchQueue? = nil,
  465. options: JSONSerialization.ReadingOptions = .allowFragments,
  466. completionHandler: @escaping (DataResponse<Any>) -> Void)
  467. -> Self
  468. {
  469. return response(
  470. queue: queue,
  471. responseSerializer: DataRequest.jsonResponseSerializer(options: options),
  472. completionHandler: completionHandler
  473. )
  474. }
  475. }
  476. extension DownloadRequest {
  477. /// Creates a response serializer that returns a JSON object result type constructed from the response data using
  478. /// `JSONSerialization` with the specified reading options.
  479. ///
  480. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  481. ///
  482. /// - returns: A JSON object response serializer.
  483. public static func jsonResponseSerializer(
  484. options: JSONSerialization.ReadingOptions = .allowFragments)
  485. -> DownloadResponseSerializer<Any>
  486. {
  487. return DownloadResponseSerializer { _, response, fileURL, error in
  488. guard error == nil else { return .failure(error!) }
  489. guard let fileURL = fileURL else {
  490. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  491. }
  492. do {
  493. let data = try Data(contentsOf: fileURL)
  494. return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
  495. } catch {
  496. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  497. }
  498. }
  499. }
  500. /// Adds a handler to be called once the request has finished.
  501. ///
  502. /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
  503. /// - parameter completionHandler: A closure to be executed once the request has finished.
  504. ///
  505. /// - returns: The request.
  506. @discardableResult
  507. public func responseJSON(
  508. queue: DispatchQueue? = nil,
  509. options: JSONSerialization.ReadingOptions = .allowFragments,
  510. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  511. -> Self
  512. {
  513. return response(
  514. queue: queue,
  515. responseSerializer: DownloadRequest.jsonResponseSerializer(options: options),
  516. completionHandler: completionHandler
  517. )
  518. }
  519. }
  520. // MARK: - Property List
  521. extension Request {
  522. /// Returns a plist object contained in a result type constructed from the response data using
  523. /// `PropertyListSerialization` with the specified reading options.
  524. ///
  525. /// - parameter options: The property list reading options. Defaults to `[]`.
  526. /// - parameter response: The response from the server.
  527. /// - parameter data: The data returned from the server.
  528. /// - parameter error: The error already encountered if it exists.
  529. ///
  530. /// - returns: The result data type.
  531. public static func serializeResponsePropertyList(
  532. options: PropertyListSerialization.ReadOptions,
  533. response: HTTPURLResponse?,
  534. data: Data?,
  535. error: Error?)
  536. -> Result<Any>
  537. {
  538. guard error == nil else { return .failure(error!) }
  539. if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
  540. guard let validData = data, validData.count > 0 else {
  541. return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
  542. }
  543. do {
  544. let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
  545. return .success(plist)
  546. } catch {
  547. return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
  548. }
  549. }
  550. }
  551. extension DataRequest {
  552. /// Creates a response serializer that returns an object constructed from the response data using
  553. /// `PropertyListSerialization` with the specified reading options.
  554. ///
  555. /// - parameter options: The property list reading options. Defaults to `[]`.
  556. ///
  557. /// - returns: A property list object response serializer.
  558. public static func propertyListResponseSerializer(
  559. options: PropertyListSerialization.ReadOptions = [])
  560. -> DataResponseSerializer<Any>
  561. {
  562. return DataResponseSerializer { _, response, data, error in
  563. return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
  564. }
  565. }
  566. /// Adds a handler to be called once the request has finished.
  567. ///
  568. /// - parameter options: The property list reading options. Defaults to `[]`.
  569. /// - parameter completionHandler: A closure to be executed once the request has finished.
  570. ///
  571. /// - returns: The request.
  572. @discardableResult
  573. public func responsePropertyList(
  574. queue: DispatchQueue? = nil,
  575. options: PropertyListSerialization.ReadOptions = [],
  576. completionHandler: @escaping (DataResponse<Any>) -> Void)
  577. -> Self
  578. {
  579. return response(
  580. queue: queue,
  581. responseSerializer: DataRequest.propertyListResponseSerializer(options: options),
  582. completionHandler: completionHandler
  583. )
  584. }
  585. }
  586. extension DownloadRequest {
  587. /// Creates a response serializer that returns an object constructed from the response data using
  588. /// `PropertyListSerialization` with the specified reading options.
  589. ///
  590. /// - parameter options: The property list reading options. Defaults to `[]`.
  591. ///
  592. /// - returns: A property list object response serializer.
  593. public static func propertyListResponseSerializer(
  594. options: PropertyListSerialization.ReadOptions = [])
  595. -> DownloadResponseSerializer<Any>
  596. {
  597. return DownloadResponseSerializer { _, response, fileURL, error in
  598. guard error == nil else { return .failure(error!) }
  599. guard let fileURL = fileURL else {
  600. return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
  601. }
  602. do {
  603. let data = try Data(contentsOf: fileURL)
  604. return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
  605. } catch {
  606. return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
  607. }
  608. }
  609. }
  610. /// Adds a handler to be called once the request has finished.
  611. ///
  612. /// - parameter options: The property list reading options. Defaults to `[]`.
  613. /// - parameter completionHandler: A closure to be executed once the request has finished.
  614. ///
  615. /// - returns: The request.
  616. @discardableResult
  617. public func responsePropertyList(
  618. queue: DispatchQueue? = nil,
  619. options: PropertyListSerialization.ReadOptions = [],
  620. completionHandler: @escaping (DownloadResponse<Any>) -> Void)
  621. -> Self
  622. {
  623. return response(
  624. queue: queue,
  625. responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options),
  626. completionHandler: completionHandler
  627. )
  628. }
  629. }
  630. /// A set of HTTP response status code that do not contain response data.
  631. private let emptyDataStatusCodes: Set<Int> = [204, 205]