Skip to content

Commit e4f63e8

Browse files
committed
Merge branch 'development'
* development: Remove unnecessary function calls. Fix build Don’t create empty closures when we don’t need them. Fixes #1118. Propagate http header callback from websocket back to client. clean up emit completion code update cartfile too update deps: Fix #1105 update xcode settings convert SocketData to serialisable socket representation Add a variadic method for emit completion handlers in swift no need to capture completion hander in wrapper wrap completion handler to run on handleQueue add optional write completion handler for emit's
2 parents 016e127 + ec86a19 commit e4f63e8

16 files changed

+155
-68
lines changed

Diff for: Cartfile.resolved

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
github "daltoniam/Starscream" "3.0.5"
1+
github "daltoniam/Starscream" "3.0.6"

Diff for: Package.resolved

+2-20
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,13 @@
11
{
22
"object": {
33
"pins": [
4-
{
5-
"package": "SSCommonCrypto",
6-
"repositoryURL": "https://github.com/daltoniam/common-crypto-spm",
7-
"state": {
8-
"branch": null,
9-
"revision": "2eb3aff0fb57f92f5722fac5d6d20bf64669ca66",
10-
"version": "1.1.0"
11-
}
12-
},
134
{
145
"package": "Starscream",
156
"repositoryURL": "https://github.com/daltoniam/Starscream",
167
"state": {
178
"branch": null,
18-
"revision": "114e5df9b6251970a069e8f1c0cbb5802759f0a9",
19-
"version": "3.0.5"
20-
}
21-
},
22-
{
23-
"package": "SSCZLib",
24-
"repositoryURL": "https://github.com/daltoniam/zlib-spm.git",
25-
"state": {
26-
"branch": null,
27-
"revision": "83ac8d719a2f3aa775dbdf116a57f56fb2c49abb",
28-
"version": "1.1.0"
9+
"revision": "ebdc260ea64e68f7569c62e8744b5cd15d3a49d6",
10+
"version": "3.0.6"
2911
}
3012
}
3113
]

Diff for: Socket.IO-Client-Swift.xcodeproj/project.pbxproj

+7-3
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@
391391
attributes = {
392392
LastSwiftMigration = 0730;
393393
LastSwiftUpdateCheck = 0730;
394-
LastUpgradeCheck = 0900;
394+
LastUpgradeCheck = 1000;
395395
TargetAttributes = {
396396
572EF2371B51F18A00EEBB58 = {
397397
CreatedOnToolsVersion = 6.4;
@@ -523,18 +523,20 @@
523523
CLANG_WARN_BOOL_CONVERSION = YES;
524524
CLANG_WARN_COMMA = YES;
525525
CLANG_WARN_CONSTANT_CONVERSION = YES;
526+
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
526527
CLANG_WARN_EMPTY_BODY = YES;
527528
CLANG_WARN_ENUM_CONVERSION = YES;
528529
CLANG_WARN_INFINITE_RECURSION = YES;
529530
CLANG_WARN_INT_CONVERSION = YES;
530531
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
532+
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
531533
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
532534
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
533535
CLANG_WARN_STRICT_PROTOTYPES = YES;
534536
CLANG_WARN_SUSPICIOUS_MOVE = YES;
535537
CLANG_WARN_UNREACHABLE_CODE = YES;
536538
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
537-
CODE_SIGN_IDENTITY = "Developer ID Application";
539+
CODE_SIGN_IDENTITY = "Mac Developer";
538540
ENABLE_BITCODE = YES;
539541
"ENABLE_BITCODE[sdk=macosx*]" = NO;
540542
ENABLE_STRICT_OBJC_MSGSEND = YES;
@@ -596,18 +598,20 @@
596598
CLANG_WARN_BOOL_CONVERSION = YES;
597599
CLANG_WARN_COMMA = YES;
598600
CLANG_WARN_CONSTANT_CONVERSION = YES;
601+
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
599602
CLANG_WARN_EMPTY_BODY = YES;
600603
CLANG_WARN_ENUM_CONVERSION = YES;
601604
CLANG_WARN_INFINITE_RECURSION = YES;
602605
CLANG_WARN_INT_CONVERSION = YES;
603606
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
607+
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
604608
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
605609
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
606610
CLANG_WARN_STRICT_PROTOTYPES = YES;
607611
CLANG_WARN_SUSPICIOUS_MOVE = YES;
608612
CLANG_WARN_UNREACHABLE_CODE = YES;
609613
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
610-
CODE_SIGN_IDENTITY = "Developer ID Application";
614+
CODE_SIGN_IDENTITY = "Mac Developer";
611615
ENABLE_BITCODE = YES;
612616
"ENABLE_BITCODE[sdk=macosx*]" = NO;
613617
ENABLE_STRICT_OBJC_MSGSEND = YES;

Diff for: Socket.IO-Client-Swift.xcodeproj/xcshareddata/xcschemes/SocketIO.xcscheme

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<Scheme
3-
LastUpgradeVersion = "0900"
3+
LastUpgradeVersion = "1000"
44
version = "1.3">
55
<BuildAction
66
parallelizeBuildables = "YES"
@@ -40,7 +40,6 @@
4040
buildConfiguration = "Debug"
4141
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
4242
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
43-
language = ""
4443
shouldUseLaunchSchemeArgsEnv = "YES">
4544
<Testables>
4645
<TestableReference
@@ -70,7 +69,6 @@
7069
buildConfiguration = "Debug"
7170
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
7271
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
73-
language = ""
7472
launchStyle = "0"
7573
useCustomWorkingDirectory = "NO"
7674
ignoresPersistentStateOnLaunch = "NO"

Diff for: Source/SocketIO/Client/SocketIOClient.swift

+30-5
Original file line numberDiff line numberDiff line change
@@ -204,16 +204,17 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
204204
leaveNamespace()
205205
}
206206

207-
/// Send an event to the server, with optional data items.
207+
/// Send an event to the server, with optional data items and optional write completion handler.
208208
///
209209
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
210210
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
211211
///
212212
/// - parameter event: The event to send.
213213
/// - parameter items: The items to send with this event. May be left out.
214-
open func emit(_ event: String, _ items: SocketData...) {
214+
/// - parameter completion: Callback called on transport write completion.
215+
open func emit(_ event: String, _ items: SocketData..., completion: (() -> ())? = nil) {
215216
do {
216-
try emit(event, with: items.map({ try $0.socketRepresentation() }))
217+
try emit(event, with: items.map({ try $0.socketRepresentation() }), completion: completion)
217218
} catch {
218219
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
219220
type: logType)
@@ -231,6 +232,16 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
231232
emit([event] + items)
232233
}
233234

235+
/// Same as emit, but meant for Objective-C
236+
///
237+
/// - parameter event: The event to send.
238+
/// - parameter items: The items to send with this event. Send an empty array to send no data.
239+
/// - parameter completion: Callback called on transport write completion.
240+
@objc
241+
open func emit(_ event: String, with items: [Any], completion: (() -> ())? = nil) {
242+
emit([event] + items, completion: completion)
243+
}
244+
234245
/// Sends a message to the server, requesting an ack.
235246
///
236247
/// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack.
@@ -284,8 +295,22 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
284295
return createOnAck([event] + items)
285296
}
286297

287-
func emit(_ data: [Any], ack: Int? = nil, binary: Bool = true, isAck: Bool = false) {
298+
func emit(_ data: [Any],
299+
ack: Int? = nil,
300+
binary: Bool = true,
301+
isAck: Bool = false,
302+
completion: (() -> ())? = nil
303+
) {
304+
// wrap the completion handler so it always runs async via handlerQueue
305+
let wrappedCompletion: (() -> ())? = (completion == nil) ? nil : {[weak self] in
306+
guard let this = self else { return }
307+
this.manager?.handleQueue.async {
308+
completion!()
309+
}
310+
}
311+
288312
guard status == .connected else {
313+
wrappedCompletion?()
289314
handleClientEvent(.error, data: ["Tried emitting when not connected"])
290315
return
291316
}
@@ -295,7 +320,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
295320

296321
DefaultSocketLogger.Logger.log("Emitting: \(str), Ack: \(isAck)", type: logType)
297322

298-
manager?.engine?.send(str, withData: packet.binary)
323+
manager?.engine?.send(str, withData: packet.binary, completion: wrappedCompletion)
299324
}
300325

301326
/// Call when you wish to tell the server that you've received the event for `ack`.

Diff for: Source/SocketIO/Client/SocketIOClientSpec.swift

+15-2
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,15 @@ public protocol SocketIOClientSpec : AnyObject {
9292
/// Disconnects the socket.
9393
func disconnect()
9494

95-
/// Send an event to the server, with optional data items.
95+
/// Send an event to the server, with optional data items and optional write completion handler.
9696
///
9797
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
9898
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
9999
///
100100
/// - parameter event: The event to send.
101101
/// - parameter items: The items to send with this event. May be left out.
102-
func emit(_ event: String, _ items: SocketData...)
102+
/// - parameter completion: Callback called on transport write completion.
103+
func emit(_ event: String, _ items: SocketData..., completion: (() -> ())?)
103104

104105
/// Call when you wish to tell the server that you've received the event for `ack`.
105106
///
@@ -334,4 +335,16 @@ public enum SocketClientEvent : String {
334335
/// }
335336
/// ```
336337
case statusChange
338+
339+
/// Emitted when when upgrading the http connection to a websocket connection.
340+
///
341+
/// Usage:
342+
///
343+
/// ```swift
344+
/// socket.on(clientEvent: .websocketUpgrade) {data, ack in
345+
/// let headers = (data as [Any])[0]
346+
/// // Some header logic
347+
/// }
348+
/// ```
349+
case websocketUpgrade
337350
}

Diff for: Source/SocketIO/Engine/SocketEngine.swift

+26-14
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
4949
/// A queue of engine.io messages waiting for POSTing
5050
///
5151
/// **You should not touch this directly**
52-
public var postWait = [String]()
52+
public var postWait = [Post]()
5353

5454
/// `true` if there is an outstanding poll. Trying to poll before the first is done will cause socket.io to
5555
/// disconnect us.
@@ -313,6 +313,12 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
313313
this.parseEngineMessage(message)
314314
}
315315

316+
ws?.onHttpResponseHeaders = {[weak self] headers in
317+
guard let this = self else { return }
318+
319+
this.client?.engineDidWebsocketUpgrade(headers: headers)
320+
}
321+
316322
ws?.connect()
317323
}
318324

@@ -340,15 +346,15 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
340346
if polling {
341347
disconnectPolling(reason: reason)
342348
} else {
343-
sendWebSocketMessage("", withType: .close, withData: [])
349+
sendWebSocketMessage("", withType: .close, withData: [], completion: nil)
344350
closeOutEngine(reason: reason)
345351
}
346352
}
347353

348354
// We need to take special care when we're polling that we send it ASAP
349355
// Also make sure we're on the emitQueue since we're touching postWait
350356
private func disconnectPolling(reason: String) {
351-
postWait.append(String(SocketEnginePacketType.close.rawValue))
357+
postWait.append((String(SocketEnginePacketType.close.rawValue), {}))
352358

353359
doRequest(for: createRequestForPostWithPostWait()) {_, _, _ in }
354360
closeOutEngine(reason: reason)
@@ -366,7 +372,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
366372

367373
DefaultSocketLogger.Logger.log("Switching to WebSockets", type: SocketEngine.logType)
368374

369-
sendWebSocketMessage("", withType: .upgrade, withData: [])
375+
sendWebSocketMessage("", withType: .upgrade, withData: [], completion: nil)
370376
polling = false
371377
fastUpgrade = false
372378
probing = false
@@ -384,7 +390,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
384390
DefaultSocketLogger.Logger.log("Flushing probe wait", type: SocketEngine.logType)
385391

386392
for waiter in probeWait {
387-
write(waiter.msg, withType: waiter.type, withData: waiter.data)
393+
write(waiter.msg, withType: waiter.type, withData: waiter.data, completion: waiter.completion)
388394
}
389395

390396
probeWait.removeAll(keepingCapacity: false)
@@ -398,7 +404,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
398404
guard let ws = self.ws else { return }
399405

400406
for msg in postWait {
401-
ws.write(string: msg)
407+
ws.write(string: msg.msg, completion: msg.completion)
402408
}
403409

404410
postWait.removeAll(keepingCapacity: false)
@@ -544,7 +550,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
544550
}
545551

546552
pongsMissed += 1
547-
write("", withType: .ping, withData: [])
553+
write("", withType: .ping, withData: [], completion: nil)
548554

549555
engineQueue.asyncAfter(deadline: .now() + .milliseconds(pingInterval)) {[weak self, id = self.sid] in
550556
// Make sure not to ping old connections
@@ -600,7 +606,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
600606
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: SocketEngine.logType)
601607

602608
fastUpgrade = true
603-
sendPollMessage("", withType: .noop, withData: [])
609+
sendPollMessage("", withType: .noop, withData: [], completion: nil)
604610
// After this point, we should not send anymore polling messages
605611
}
606612
}
@@ -610,23 +616,27 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
610616
/// - parameter msg: The message to send.
611617
/// - parameter type: The type of this message.
612618
/// - parameter data: Any data that this message has.
613-
open func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) {
619+
/// - parameter completion: Callback called on transport write completion.
620+
open func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: (() -> ())? = nil) {
614621
engineQueue.async {
615-
guard self.connected else { return }
622+
guard self.connected else {
623+
completion?()
624+
return
625+
}
616626
guard !self.probing else {
617-
self.probeWait.append((msg, type, data))
627+
self.probeWait.append((msg, type, data, completion))
618628

619629
return
620630
}
621631

622632
if self.polling {
623633
DefaultSocketLogger.Logger.log("Writing poll: \(msg) has data: \(data.count != 0)",
624634
type: SocketEngine.logType)
625-
self.sendPollMessage(msg, withType: type, withData: data)
635+
self.sendPollMessage(msg, withType: type, withData: data, completion: completion)
626636
} else {
627637
DefaultSocketLogger.Logger.log("Writing ws: \(msg) has data: \(data.count != 0)",
628638
type: SocketEngine.logType)
629-
self.sendWebSocketMessage(msg, withType: type, withData: data)
639+
self.sendWebSocketMessage(msg, withType: type, withData: data, completion: completion)
630640
}
631641
}
632642
}
@@ -662,7 +672,9 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
662672
connected = false
663673
polling = true
664674

665-
if let reason = error?.localizedDescription {
675+
if let error = error as? WSError {
676+
didError(reason: "\(error.message). code=\(error.code), type=\(error.type)")
677+
} else if let reason = error?.localizedDescription {
666678
didError(reason: reason)
667679
} else {
668680
client?.engineDidClose(reason: "Socket Disconnected")

Diff for: Source/SocketIO/Engine/SocketEngineClient.swift

+5
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,9 @@ import Foundation
5959
///
6060
/// - parameter data: The data the engine received.
6161
func parseEngineBinaryData(_ data: Data)
62+
63+
/// Called when when upgrading the http connection to a websocket connection.
64+
///
65+
/// - parameter headers: The http headers.
66+
func engineDidWebsocketUpgrade(headers: [String: String])
6267
}

0 commit comments

Comments
 (0)