Skip to content

Commit 83cee79

Browse files
committed
Merge pull request #212 from socketio/better-options
Better options
2 parents 7f443fa + 86bd271 commit 83cee79

File tree

6 files changed

+193
-61
lines changed

6 files changed

+193
-61
lines changed

README.md

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Socket.IO-client for iOS/OS X.
55

66
##Example
77
```swift
8-
let socket = SocketIOClient(socketURL: "localhost:8080")
8+
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
99

1010
socket.on("connect") {data, ack in
1111
print("socket connected")
@@ -26,7 +26,7 @@ socket.connect()
2626

2727
##Objective-C Example
2828
```objective-c
29-
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" opts:nil];
29+
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
3030

3131
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
3232
NSLog(@"socket connected");
@@ -120,25 +120,29 @@ Run `seed install`.
120120
##API
121121
Constructors
122122
-----------
123-
`init(socketURL: String, opts: NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values) note: If your socket.io server is secure, you need to specify `https` in your socketURL.
123+
`init(var socketURL: String, options: Set<SocketIOClientOption>? = nil)` - Creates a new SocketIOClient. opts is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
124+
`convenience init(socketURL: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
124125

125126
Options
126127
-------
127-
- `connectParams: [String: AnyObject]?` - Dictionary whose contents will be passed with the connection.
128-
- `reconnects: Bool` Default is `true`
129-
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
130-
- `reconnectWait: Int` Default is `10`
131-
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
132-
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
133-
- `nsp: String` Default is `"/"`. Connects to a namespace.
134-
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
135-
- `log: Bool` If `true` socket will log debug messages. Default is false.
136-
- `logger: SocketLogger` If you wish to implement your own logger that conforms to SocketLogger you can pass it in here. Will use the default logging defined under the protocol otherwise.
137-
- `sessionDelegate: NSURLSessionDelegate` Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
138-
- `path: String` - If the server uses a custom path. ex: `"/swift"`. Default is `""`
139-
- `extraHeaders: [String: String]?` - Adds custom headers to the initial request. Default is nil.
140-
- `handleQueue: dispatch_queue_t` - The dispatch queue that handlers are run on. Default is the main queue.
128+
All options are a case of SocketIOClientOption. To get the Objective-C Option, convert the name to lowerCamelCase.
141129

130+
```swift
131+
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
132+
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
133+
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
134+
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
135+
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
136+
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
137+
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
138+
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
139+
case Log(Bool) // If `true` socket will log debug messages. Default is false.
140+
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
141+
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
142+
case Path(String) // If the server uses a custom path. ex: `"/swift"`. Default is `""`
143+
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
144+
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
145+
```
142146
Methods
143147
-------
144148
1. `on(event: String, callback: NormalCallback)` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
@@ -154,6 +158,8 @@ Methods
154158
11. `reconnect()` - Causes the client to reconnect to the server.
155159
12. `joinNamespace()` - Causes the client to join nsp. Shouldn't need to be called unless you change nsp manually.
156160
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
161+
14. `off(event: String)` - Removes all event handlers for event.
162+
15. `removeAllHandlers()` - Removes all handlers.
157163

158164
Client Events
159165
------

Socket.IO-Client-Swift.xcodeproj/project.pbxproj

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@
3737
5764DFA01B51F254004FF46E /* SwiftRegex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5764DF871B51F254004FF46E /* SwiftRegex.swift */; };
3838
5764DFA11B51F254004FF46E /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5764DF881B51F254004FF46E /* WebSocket.swift */; };
3939
5764DFA21B51F254004FF46E /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5764DF881B51F254004FF46E /* WebSocket.swift */; };
40+
740E10441BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */; settings = {ASSET_TAGS = (); }; };
41+
740E10451BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */; settings = {ASSET_TAGS = (); }; };
42+
740E10461BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */; settings = {ASSET_TAGS = (); }; };
43+
740E10471BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */; settings = {ASSET_TAGS = (); }; };
4044
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; settings = {ASSET_TAGS = (); }; };
4145
741F39EF1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; settings = {ASSET_TAGS = (); }; };
4246
745895381BB59A0A0050ACC8 /* SocketAckManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94A20D601B99E22F00BF9E44 /* SocketAckManagerTest.swift */; };
@@ -138,6 +142,7 @@
138142
5764DF861B51F254004FF46E /* SocketTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketTypes.swift; path = SocketIOClientSwift/SocketTypes.swift; sourceTree = "<group>"; };
139143
5764DF871B51F254004FF46E /* SwiftRegex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftRegex.swift; path = SocketIOClientSwift/SwiftRegex.swift; sourceTree = "<group>"; };
140144
5764DF881B51F254004FF46E /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = SocketIOClientSwift/WebSocket.swift; sourceTree = "<group>"; };
145+
740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientOption.swift; path = SocketIOClientSwift/SocketIOClientOption.swift; sourceTree = "<group>"; };
141146
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = "<group>"; };
142147
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
143148
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketSideEffectTest.swift; sourceTree = "<group>"; };
@@ -293,6 +298,7 @@
293298
5764DF801B51F254004FF46E /* SocketEventHandler.swift */,
294299
5764DF811B51F254004FF46E /* SocketFixUTF8.swift */,
295300
5764DF821B51F254004FF46E /* SocketIOClient.swift */,
301+
740E10431BD2C4680064FC4A /* SocketIOClientOption.swift */,
296302
74781D591B7E83930042CACA /* SocketIOClientStatus.swift */,
297303
5764DF831B51F254004FF46E /* SocketLogger.swift */,
298304
5764DF841B51F254004FF46E /* SocketPacket.swift */,
@@ -492,6 +498,7 @@
492498
74781D5A1B7E83930042CACA /* SocketIOClientStatus.swift in Sources */,
493499
5764DFA11B51F254004FF46E /* WebSocket.swift in Sources */,
494500
5764DF991B51F254004FF46E /* SocketPacket.swift in Sources */,
501+
740E10441BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */,
495502
74F124E31BC5697B002966F4 /* SocketEngineSpec.swift in Sources */,
496503
5764DF891B51F254004FF46E /* SocketAckManager.swift in Sources */,
497504
74F124E81BC56BFC002966F4 /* SocketEnginePacketType.swift in Sources */,
@@ -523,6 +530,7 @@
523530
74781D5B1B7E83930042CACA /* SocketIOClientStatus.swift in Sources */,
524531
945B653B1B5FCEEA0081E995 /* SocketIOClient.swift in Sources */,
525532
74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */,
533+
740E10451BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */,
526534
949FAE8D1B9B94E600073BE9 /* SocketParserTest.swift in Sources */,
527535
7472C65C1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */,
528536
945B65411B5FCEEA0081E995 /* WebSocket.swift in Sources */,
@@ -548,6 +556,7 @@
548556
74781D5C1B7E83930042CACA /* SocketIOClientStatus.swift in Sources */,
549557
5764DFA21B51F254004FF46E /* WebSocket.swift in Sources */,
550558
5764DF9A1B51F254004FF46E /* SocketPacket.swift in Sources */,
559+
740E10461BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */,
551560
74F124E51BC5697B002966F4 /* SocketEngineSpec.swift in Sources */,
552561
5764DF8A1B51F254004FF46E /* SocketAckManager.swift in Sources */,
553562
74F124EA1BC56BFC002966F4 /* SocketEnginePacketType.swift in Sources */,
@@ -579,6 +588,7 @@
579588
745895381BB59A0A0050ACC8 /* SocketAckManagerTest.swift in Sources */,
580589
7458953D1BB59A0A0050ACC8 /* SocketParserTest.swift in Sources */,
581590
74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */,
591+
740E10471BD2C4680064FC4A /* SocketIOClientOption.swift in Sources */,
582592
74F124EB1BC56BFC002966F4 /* SocketEnginePacketType.swift in Sources */,
583593
7472C65D1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */,
584594
749A7F901BA9D42D00782993 /* SocketAckEmitter.swift in Sources */,

SocketIOClientSwift/SocketIOClient.swift

Lines changed: 38 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,15 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
3232
public private(set) var status = SocketIOClientStatus.NotConnected
3333

3434
public var nsp = "/"
35-
public var opts: [String: AnyObject]?
35+
public var options: Set<SocketIOClientOption>?
3636
public var reconnects = true
3737
public var reconnectWait = 10
3838
public var sid: String? {
3939
return engine?.sid
4040
}
4141

4242
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
43-
private let handleQueue: dispatch_queue_t!
4443
private let logType = "SocketIOClient"
45-
private let reconnectAttempts: Int!
4644

4745
private var anyHandler: ((SocketAnyEvent) -> Void)?
4846
private var currentReconnectAttempt = 0
@@ -52,12 +50,14 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
5250
private var ackHandlers = SocketAckManager()
5351

5452
private(set) var currentAck = -1
53+
private(set) var handleQueue = dispatch_get_main_queue()
54+
private(set) var reconnectAttempts = -1
5555
var waitingData = [SocketPacket]()
5656

5757
/**
58-
Create a new SocketIOClient. opts can be omitted
58+
Type safe way to create a new SocketIOClient. opts can be omitted
5959
*/
60-
public init(var socketURL: String, opts: [String: AnyObject]? = nil) {
60+
public init(var socketURL: String, options: Set<SocketIOClientOption>? = nil) {
6161
if socketURL["https://"].matches().count != 0 {
6262
self.secure = true
6363
}
@@ -66,55 +66,52 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
6666
socketURL = socketURL["https://"] ~= ""
6767

6868
self.socketURL = socketURL
69-
self.opts = opts
69+
self.options = options
7070

71-
if let connectParams = opts?["connectParams"] as? [String: AnyObject] {
72-
self.connectParams = connectParams
73-
}
74-
75-
if let logger = opts?["logger"] as? SocketLogger {
76-
Logger = logger
77-
}
78-
79-
if let log = opts?["log"] as? Bool {
80-
Logger.log = log
81-
}
82-
83-
if let nsp = opts?["nsp"] as? String {
84-
self.nsp = nsp
85-
}
86-
87-
if let reconnects = opts?["reconnects"] as? Bool {
88-
self.reconnects = reconnects
89-
}
90-
91-
if let reconnectAttempts = opts?["reconnectAttempts"] as? Int {
92-
self.reconnectAttempts = reconnectAttempts
93-
} else {
94-
self.reconnectAttempts = -1
95-
}
96-
97-
if let reconnectWait = opts?["reconnectWait"] as? Int {
98-
self.reconnectWait = abs(reconnectWait)
99-
}
100-
101-
if let handleQueue = opts?["handleQueue"] as? dispatch_queue_t {
102-
self.handleQueue = handleQueue
103-
} else {
104-
self.handleQueue = dispatch_get_main_queue()
71+
for option in options ?? [] {
72+
switch option {
73+
case .ConnectParams(let params):
74+
connectParams = params
75+
case .Reconnects(let reconnects):
76+
self.reconnects = reconnects
77+
case .ReconnectAttempts(let attempts):
78+
reconnectAttempts = attempts
79+
case .ReconnectWait(let wait):
80+
reconnectWait = abs(wait)
81+
case .Nsp(let nsp):
82+
self.nsp = nsp
83+
case .Log(let log):
84+
Logger.log = log
85+
case .Logger(let logger):
86+
Logger = logger
87+
case .HandleQueue(let queue):
88+
handleQueue = queue
89+
default:
90+
continue
91+
}
10592
}
10693

10794
super.init()
10895
}
10996

97+
/**
98+
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
99+
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
100+
*/
101+
public convenience init(socketURL: String, options: NSDictionary?) {
102+
self.init(socketURL: socketURL,
103+
options: SocketIOClientOption.NSDictionaryToSocketOptionsSet(options ?? [:]))
104+
}
105+
110106
deinit {
111107
Logger.log("Client is being deinit", type: logType)
112108
}
113109

114110
private func addEngine() -> SocketEngine {
115111
Logger.log("Adding engine", type: logType)
116112

117-
let newEngine = SocketEngine(client: self, opts: opts)
113+
let newEngine = SocketEngine(client: self, opts:
114+
SocketIOClientOption.SocketOptionsSetToNSDictionary(options ?? []))
118115

119116
engine = newEngine
120117
return newEngine
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
//
2+
// SocketIOClientOption .swift
3+
// Socket.IO-Client-Swift
4+
//
5+
// Created by Erik Little on 10/17/15.
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+
25+
import Foundation
26+
27+
public enum SocketIOClientOption: CustomStringConvertible, Hashable {
28+
case ConnectParams([String: AnyObject])
29+
case Reconnects(Bool)
30+
case ReconnectAttempts(Int)
31+
case ReconnectWait(Int)
32+
case ForcePolling(Bool)
33+
case ForceWebsockets(Bool)
34+
case Nsp(String)
35+
case Cookies([NSHTTPCookie])
36+
case Log(Bool)
37+
case Logger(SocketLogger)
38+
case SessionDelegate(NSURLSessionDelegate)
39+
case Path(String)
40+
case ExtraHeaders([String: String])
41+
case HandleQueue(dispatch_queue_t)
42+
43+
public var description: String {
44+
if let label = Mirror(reflecting: self).children.first?.label {
45+
return String(label[label.startIndex]).lowercaseString + String(label.characters.dropFirst())
46+
} else {
47+
return ""
48+
}
49+
}
50+
51+
public var hashValue: Int {
52+
return description.hashValue
53+
}
54+
55+
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
56+
switch key {
57+
case "connectParams" where value is [String: AnyObject]:
58+
return .ConnectParams(value as! [String: AnyObject])
59+
case "reconnects" where value is Bool:
60+
return .Reconnects(value as! Bool)
61+
case "reconnectAttempts" where value is Int:
62+
return .ReconnectAttempts(value as! Int)
63+
case "reconnectWait" where value is Int:
64+
return .ReconnectWait(value as! Int)
65+
case "forcePolling" where value is Bool:
66+
return .ForcePolling(value as! Bool)
67+
case "forceWebsockets" where value is Bool:
68+
return .ForceWebsockets(value as! Bool)
69+
case "nsp" where value is String:
70+
return .Nsp(value as! String)
71+
case "cookies" where value is [NSHTTPCookie]:
72+
return .Cookies(value as! [NSHTTPCookie])
73+
case "log" where value is Bool:
74+
return .Log(value as! Bool)
75+
case "logger" where value is SocketLogger:
76+
return .Logger(value as! SocketLogger)
77+
case "sessionDelegate" where value is NSURLSessionDelegate:
78+
return .SessionDelegate(value as! NSURLSessionDelegate)
79+
case "path" where value is String:
80+
return .Path(value as! String)
81+
case "extraHeaders" where value is [String: String]:
82+
return .ExtraHeaders(value as! [String: String])
83+
case "handleQueue" where value is dispatch_queue_t:
84+
return .HandleQueue(value as! dispatch_queue_t)
85+
default:
86+
return nil
87+
}
88+
}
89+
90+
func getSocketIOOptionValue() -> AnyObject? {
91+
return Mirror(reflecting: self).children.first?.value as? AnyObject
92+
}
93+
94+
static func NSDictionaryToSocketOptionsSet(dict: NSDictionary) -> Set<SocketIOClientOption> {
95+
var options = Set<SocketIOClientOption>()
96+
97+
for (rawKey, value) in dict {
98+
if let key = rawKey as? String, opt = keyValueToSocketIOClientOption(key, value: value) {
99+
options.insert(opt)
100+
}
101+
}
102+
103+
return options
104+
}
105+
106+
static func SocketOptionsSetToNSDictionary(set: Set<SocketIOClientOption>) -> NSDictionary {
107+
let options = NSMutableDictionary()
108+
109+
for option in set {
110+
options[option.description] = option.getSocketIOOptionValue()
111+
}
112+
113+
return options
114+
}
115+
}
116+
117+
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
118+
return lhs.description == rhs.description
119+
}

0 commit comments

Comments
 (0)