You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
4.8 KiB

5 years ago
  1. //
  2. // SocketExtensions.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 7/1/2016.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import Foundation
  25. import Starscream
  26. enum JSONError : Error {
  27. case notArray
  28. case notNSDictionary
  29. }
  30. extension Array {
  31. func toJSON() throws -> Data {
  32. return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
  33. }
  34. }
  35. extension CharacterSet {
  36. static var allowedURLCharacterSet: CharacterSet {
  37. return CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]\" {}^").inverted
  38. }
  39. }
  40. extension Dictionary where Key == String, Value == Any {
  41. private static func keyValueToSocketIOClientOption(key: String, value: Any) -> SocketIOClientOption? {
  42. switch (key, value) {
  43. case let ("connectParams", params as [String: Any]):
  44. return .connectParams(params)
  45. case let ("cookies", cookies as [HTTPCookie]):
  46. return .cookies(cookies)
  47. case let ("extraHeaders", headers as [String: String]):
  48. return .extraHeaders(headers)
  49. case let ("forceNew", force as Bool):
  50. return .forceNew(force)
  51. case let ("forcePolling", force as Bool):
  52. return .forcePolling(force)
  53. case let ("forceWebsockets", force as Bool):
  54. return .forceWebsockets(force)
  55. case let ("handleQueue", queue as DispatchQueue):
  56. return .handleQueue(queue)
  57. case let ("log", log as Bool):
  58. return .log(log)
  59. case let ("logger", logger as SocketLogger):
  60. return .logger(logger)
  61. case let ("path", path as String):
  62. return .path(path)
  63. case let ("reconnects", reconnects as Bool):
  64. return .reconnects(reconnects)
  65. case let ("reconnectAttempts", attempts as Int):
  66. return .reconnectAttempts(attempts)
  67. case let ("reconnectWait", wait as Int):
  68. return .reconnectWait(wait)
  69. case let ("reconnectWaitMax", wait as Int):
  70. return .reconnectWaitMax(wait)
  71. case let ("randomizationFactor", factor as Double):
  72. return .randomizationFactor(factor)
  73. case let ("secure", secure as Bool):
  74. return .secure(secure)
  75. case let ("security", security as SSLSecurity):
  76. return .security(security)
  77. case let ("selfSigned", selfSigned as Bool):
  78. return .selfSigned(selfSigned)
  79. case let ("sessionDelegate", delegate as URLSessionDelegate):
  80. return .sessionDelegate(delegate)
  81. case let ("compress", compress as Bool):
  82. return compress ? .compress : nil
  83. default:
  84. return nil
  85. }
  86. }
  87. func toSocketConfiguration() -> SocketIOClientConfiguration {
  88. var options = [] as SocketIOClientConfiguration
  89. for (rawKey, value) in self {
  90. if let opt = Dictionary.keyValueToSocketIOClientOption(key: rawKey, value: value) {
  91. options.insert(opt)
  92. }
  93. }
  94. return options
  95. }
  96. }
  97. extension String {
  98. func toArray() throws -> [Any] {
  99. guard let stringData = data(using: .utf16, allowLossyConversion: false) else { return [] }
  100. guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
  101. throw JSONError.notArray
  102. }
  103. return array
  104. }
  105. func toDictionary() throws -> [String: Any] {
  106. guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] }
  107. guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? [String: Any] else {
  108. throw JSONError.notNSDictionary
  109. }
  110. return json
  111. }
  112. func urlEncode() -> String? {
  113. return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
  114. }
  115. }