SocketExtensions.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. case let ("enableSOCKSProxy", enable as Bool):
  84. return .enableSOCKSProxy(enable)
  85. default:
  86. return nil
  87. }
  88. }
  89. func toSocketConfiguration() -> SocketIOClientConfiguration {
  90. var options = [] as SocketIOClientConfiguration
  91. for (rawKey, value) in self {
  92. if let opt = Dictionary.keyValueToSocketIOClientOption(key: rawKey, value: value) {
  93. options.insert(opt)
  94. }
  95. }
  96. return options
  97. }
  98. }
  99. extension String {
  100. func toArray() throws -> [Any] {
  101. guard let stringData = data(using: .utf16, allowLossyConversion: false) else { return [] }
  102. guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
  103. throw JSONError.notArray
  104. }
  105. return array
  106. }
  107. func toDictionary() throws -> [String: Any] {
  108. guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] }
  109. guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? [String: Any] else {
  110. throw JSONError.notNSDictionary
  111. }
  112. return json
  113. }
  114. func urlEncode() -> String? {
  115. return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
  116. }
  117. }