Validation.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Validation.swift
  2. //
  3. // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. extension Request {
  24. /**
  25. Used to represent whether validation was successful or encountered an error resulting in a failure.
  26. - Success: The validation was successful.
  27. - Failure: The validation failed encountering the provided error.
  28. */
  29. public enum ValidationResult {
  30. case Success
  31. case Failure(NSError)
  32. }
  33. /**
  34. A closure used to validate a request that takes a URL request and URL response, and returns whether the
  35. request was valid.
  36. */
  37. public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
  38. /**
  39. Validates the request, using the specified closure.
  40. If validation fails, subsequent calls to response handlers will have an associated error.
  41. - parameter validation: A closure to validate the request.
  42. - returns: The request.
  43. */
  44. public func validate(validation: Validation) -> Self {
  45. delegate.queue.addOperationWithBlock {
  46. if let
  47. response = self.response where self.delegate.error == nil,
  48. case let .Failure(error) = validation(self.request, response)
  49. {
  50. self.delegate.error = error
  51. }
  52. }
  53. return self
  54. }
  55. // MARK: - Status Code
  56. /**
  57. Validates that the response has a status code in the specified range.
  58. If validation fails, subsequent calls to response handlers will have an associated error.
  59. - parameter range: The range of acceptable status codes.
  60. - returns: The request.
  61. */
  62. public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  63. return validate { _, response in
  64. if acceptableStatusCode.contains(response.statusCode) {
  65. return .Success
  66. } else {
  67. let failureReason = "Response status code was unacceptable: \(response.statusCode)"
  68. let error = NSError(
  69. domain: Error.Domain,
  70. code: Error.Code.StatusCodeValidationFailed.rawValue,
  71. userInfo: [
  72. NSLocalizedFailureReasonErrorKey: failureReason,
  73. Error.UserInfoKeys.StatusCode: response.statusCode
  74. ]
  75. )
  76. return .Failure(error)
  77. }
  78. }
  79. }
  80. // MARK: - Content-Type
  81. private struct MIMEType {
  82. let type: String
  83. let subtype: String
  84. init?(_ string: String) {
  85. let components: [String] = {
  86. let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  87. let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
  88. return split.componentsSeparatedByString("/")
  89. }()
  90. if let
  91. type = components.first,
  92. subtype = components.last
  93. {
  94. self.type = type
  95. self.subtype = subtype
  96. } else {
  97. return nil
  98. }
  99. }
  100. func matches(MIME: MIMEType) -> Bool {
  101. switch (type, subtype) {
  102. case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
  103. return true
  104. default:
  105. return false
  106. }
  107. }
  108. }
  109. /**
  110. Validates that the response has a content type in the specified array.
  111. If validation fails, subsequent calls to response handlers will have an associated error.
  112. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  113. - returns: The request.
  114. */
  115. public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  116. return validate { _, response in
  117. guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
  118. if let
  119. responseContentType = response.MIMEType,
  120. responseMIMEType = MIMEType(responseContentType)
  121. {
  122. for contentType in acceptableContentTypes {
  123. if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
  124. return .Success
  125. }
  126. }
  127. } else {
  128. for contentType in acceptableContentTypes {
  129. if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
  130. return .Success
  131. }
  132. }
  133. }
  134. let contentType: String
  135. let failureReason: String
  136. if let responseContentType = response.MIMEType {
  137. contentType = responseContentType
  138. failureReason = (
  139. "Response content type \"\(responseContentType)\" does not match any acceptable " +
  140. "content types: \(acceptableContentTypes)"
  141. )
  142. } else {
  143. contentType = ""
  144. failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
  145. }
  146. let error = NSError(
  147. domain: Error.Domain,
  148. code: Error.Code.ContentTypeValidationFailed.rawValue,
  149. userInfo: [
  150. NSLocalizedFailureReasonErrorKey: failureReason,
  151. Error.UserInfoKeys.ContentType: contentType
  152. ]
  153. )
  154. return .Failure(error)
  155. }
  156. }
  157. // MARK: - Automatic
  158. /**
  159. Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  160. type matches any specified in the Accept HTTP header field.
  161. If validation fails, subsequent calls to response handlers will have an associated error.
  162. - returns: The request.
  163. */
  164. public func validate() -> Self {
  165. let acceptableStatusCodes: Range<Int> = 200..<300
  166. let acceptableContentTypes: [String] = {
  167. if let accept = request?.valueForHTTPHeaderField("Accept") {
  168. return accept.componentsSeparatedByString(",")
  169. }
  170. return ["*/*"]
  171. }()
  172. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  173. }
  174. }