Validation.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014–2015 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. A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
  26. */
  27. public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> Bool
  28. /**
  29. Validates the request, using the specified closure.
  30. If validation fails, subsequent calls to response handlers will have an associated error.
  31. :param: validation A closure to validate the request.
  32. :returns: The request.
  33. */
  34. public func validate(validation: Validation) -> Self {
  35. delegate.queue.addOperationWithBlock {
  36. if self.response != nil && self.delegate.error == nil {
  37. if !validation(self.request, self.response!) {
  38. self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
  39. }
  40. }
  41. }
  42. return self
  43. }
  44. // MARK: - Status Code
  45. /**
  46. Validates that the response has a status code in the specified range.
  47. If validation fails, subsequent calls to response handlers will have an associated error.
  48. :param: range The range of acceptable status codes.
  49. :returns: The request.
  50. */
  51. public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  52. return validate { _, response in
  53. return contains(acceptableStatusCode, response.statusCode)
  54. }
  55. }
  56. // MARK: - Content-Type
  57. private struct MIMEType {
  58. let type: String
  59. let subtype: String
  60. init?(_ string: String) {
  61. let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
  62. if let type = components.first,
  63. subtype = components.last
  64. {
  65. self.type = type
  66. self.subtype = subtype
  67. } else {
  68. return nil
  69. }
  70. }
  71. func matches(MIME: MIMEType) -> Bool {
  72. switch (type, subtype) {
  73. case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
  74. return true
  75. default:
  76. return false
  77. }
  78. }
  79. }
  80. /**
  81. Validates that the response has a content type in the specified array.
  82. If validation fails, subsequent calls to response handlers will have an associated error.
  83. :param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
  84. :returns: The request.
  85. */
  86. public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  87. return validate { _, response in
  88. if let responseContentType = response.MIMEType,
  89. responseMIMEType = MIMEType(responseContentType)
  90. {
  91. for contentType in acceptableContentTypes {
  92. if let acceptableMIMEType = MIMEType(contentType)
  93. where acceptableMIMEType.matches(responseMIMEType)
  94. {
  95. return true
  96. }
  97. }
  98. }
  99. return false
  100. }
  101. }
  102. // MARK: - Automatic
  103. /**
  104. Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
  105. If validation fails, subsequent calls to response handlers will have an associated error.
  106. :returns: The request.
  107. */
  108. public func validate() -> Self {
  109. let acceptableStatusCodes: Range<Int> = 200..<300
  110. let acceptableContentTypes: [String] = {
  111. if let accept = self.request.valueForHTTPHeaderField("Accept") {
  112. return accept.componentsSeparatedByString(",")
  113. }
  114. return ["*/*"]
  115. }()
  116. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  117. }
  118. }