ResponseSerialization.swift 28 KB

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