Merge branch 'development'

* development:
  Fix manifest
  use .upToNextMajor
  see if this fixes spm
  update starscream dev
  start work on fixing spm
  bump tools versions
  Update proj for swift 4
  make build quiet
  Just use xcodebuild for swift4.0 branch
  Build swift4.0 branch
  Update xcodeproj after rebase
  Add missing @objc
  Update for latest xcode beta
  guard creating prefixless data
  Initial Swift4 work
  Rework logging protocol to use autoclosure
  Remove another NS* use
  Don't use NSDictionary
This commit is contained in:
Erik Little 2017-09-20 07:07:58 -04:00
commit fc2852d1c1
No known key found for this signature in database
GPG Key ID: 62F837E56F4E9320
22 changed files with 145 additions and 78 deletions

View File

@ -1 +1 @@
3.1 4.0

View File

@ -1,16 +1,17 @@
language: objective-c language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS xcode_scheme: SocketIO-iOS
osx_image: xcode8.3 osx_image: xcode9
branches: branches:
only: only:
- master - master
- development - development
- swift4.0
before_install: before_install:
- brew update - brew update
- brew outdated xctool || brew upgrade xctool - brew outdated xctool || brew upgrade xctool
script: script:
- xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build-for-testing -quiet - xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -quiet
- xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac run-tests --parallelize # - xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build-for-testing -quiet
# - xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac run-tests --parallelize
- swift build - swift build
#script: xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test

View File

@ -1,9 +1,16 @@
// swift-tools-version:4.0
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "SocketIO", name: "SocketIO",
dependencies: [ products: [
.Package(url: "https://github.com/nuclearace/Starscream", majorVersion: 8), .library(name: "SocketIO", targets: ["SocketIO"])
], ],
exclude: ["Source/Starscream"] dependencies: [
.package(url: "https://github.com/nuclearace/Starscream", .upToNextMajor(from: "8.0.0")),
],
targets: [
.target(name: "SocketIO", dependencies: ["StarscreamSocketIO"], exclude: ["Sources/Starscream"])
]
) )

View File

@ -21,7 +21,7 @@ Pod::Spec.new do |s|
:submodules => true :submodules => true
} }
s.pod_target_xcconfig = { s.pod_target_xcconfig = {
'SWIFT_VERSION' => '3.1' 'SWIFT_VERSION' => '4.0'
} }
s.source_files = "Source/SocketIO/**/*.swift", "Source/SocketIO/*.swift" s.source_files = "Source/SocketIO/**/*.swift", "Source/SocketIO/*.swift"
s.dependency "StarscreamSocketIO", "~> 8.0.5" s.dependency "StarscreamSocketIO", "~> 8.0.5"

View File

@ -657,7 +657,7 @@
attributes = { attributes = {
LastSwiftMigration = 0730; LastSwiftMigration = 0730;
LastSwiftUpdateCheck = 0730; LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0800; LastUpgradeCheck = 0900;
TargetAttributes = { TargetAttributes = {
572EF2181B51F16C00EEBB58 = { 572EF2181B51F16C00EEBB58 = {
CreatedOnToolsVersion = 6.4; CreatedOnToolsVersion = 6.4;
@ -667,11 +667,11 @@
}; };
572EF2371B51F18A00EEBB58 = { 572EF2371B51F18A00EEBB58 = {
CreatedOnToolsVersion = 6.4; CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0800; LastSwiftMigration = 0900;
}; };
572EF2411B51F18A00EEBB58 = { 572EF2411B51F18A00EEBB58 = {
CreatedOnToolsVersion = 6.4; CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0800; LastSwiftMigration = 0900;
}; };
}; };
}; };
@ -958,11 +958,19 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
BITCODE_GENERATION_MODE = bitcode; BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application"; CODE_SIGN_IDENTITY = "Developer ID Application";
@ -992,11 +1000,19 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
BITCODE_GENERATION_MODE = bitcode; BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application"; CODE_SIGN_IDENTITY = "Developer ID Application";
@ -1038,7 +1054,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer"; CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
@ -1071,7 +1087,7 @@
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib; SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0; SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
@ -1097,7 +1113,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Distribution"; CODE_SIGN_IDENTITY = "iPhone Distribution";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
@ -1123,7 +1139,7 @@
SDKROOT = iphoneos; SDKROOT = iphoneos;
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib; SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
SWIFT_VERSION = 3.0; SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
@ -1179,6 +1195,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_VERSION = 4.0;
}; };
name = Debug; name = Debug;
}; };
@ -1223,6 +1240,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
}; };
name = Release; name = Release;
@ -1285,7 +1303,8 @@
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = ""; SWIFT_INCLUDE_PATHS = "";
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0; SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_VERSION = 4.0;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
}; };
@ -1342,7 +1361,8 @@
SDKROOT = macosx; SDKROOT = macosx;
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = ""; SWIFT_INCLUDE_PATHS = "";
SWIFT_VERSION = 3.0; SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_VERSION = 4.0;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
}; };
@ -1403,7 +1423,8 @@
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx; SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0; SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_VERSION = 4.0;
}; };
name = Debug; name = Debug;
}; };
@ -1454,7 +1475,8 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx; SDKROOT = macosx;
SWIFT_VERSION = 3.0; SWIFT_SWIFT3_OBJC_INFERENCE = On;
SWIFT_VERSION = 4.0;
}; };
name = Release; name = Release;
}; };
@ -1476,6 +1498,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer"; CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
@ -1510,6 +1533,7 @@
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib; SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = 3; TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0; TVOS_DEPLOYMENT_TARGET = 9.0;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
@ -1535,6 +1559,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Distribution"; CODE_SIGN_IDENTITY = "iPhone Distribution";
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
@ -1562,6 +1587,7 @@
SDKROOT = appletvos; SDKROOT = appletvos;
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib; SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = 3; TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0; TVOS_DEPLOYMENT_TARGET = 9.0;
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
@ -1618,6 +1644,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos; SDKROOT = appletvos;
SWIFT_VERSION = 4.0;
}; };
name = Debug; name = Debug;
}; };
@ -1662,6 +1689,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos; SDKROOT = appletvos;
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
}; };
name = Release; name = Release;

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0800" LastUpgradeVersion = "0900"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@ -40,6 +40,7 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES"> shouldUseLaunchSchemeArgsEnv = "YES">
<Testables> <Testables>
<TestableReference <TestableReference
@ -69,6 +70,7 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0" launchStyle = "0"
useCustomWorkingDirectory = "NO" useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO" ignoresPersistentStateOnLaunch = "NO"

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0800" LastUpgradeVersion = "0900"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0800" LastUpgradeVersion = "0900"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@ -40,6 +40,7 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES"> shouldUseLaunchSchemeArgsEnv = "YES">
<Testables> <Testables>
<TestableReference <TestableReference
@ -69,6 +70,7 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0" launchStyle = "0"
useCustomWorkingDirectory = "NO" useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO" ignoresPersistentStateOnLaunch = "NO"

View File

@ -36,6 +36,8 @@
self.socket.nsp = @"/objective-c"; self.socket.nsp = @"/objective-c";
self.socket.reconnects = false; self.socket.reconnects = false;
self.socket.reconnectWait = 1; self.socket.reconnectWait = 1;
if (self.socket.status == SocketIOClientStatusConnected) { }
if (self.socket.engine == NULL) { }
} }
- (void)testOnSyntax { - (void)testOnSyntax {

View File

@ -8,6 +8,7 @@
import XCTest import XCTest
@testable import SocketIO @testable import SocketIO
@testable import StarscreamSocketIO
class SocketSideEffectTest: XCTestCase { class SocketSideEffectTest: XCTestCase {
func testInitialCurrentAck() { func testInitialCurrentAck() {

View File

@ -65,6 +65,7 @@ public final class SocketAckEmitter : NSObject {
/// Call to ack receiving this event. /// Call to ack receiving this event.
/// ///
/// - parameter items: An array of items to send when acking. Use `[]` to send nothing. /// - parameter items: An array of items to send when acking. Use `[]` to send nothing.
@objc
public func with(_ items: [Any]) { public func with(_ items: [Any]) {
guard ackNum != -1 else { return } guard ackNum != -1 else { return }
@ -104,6 +105,7 @@ public final class OnAckCallback : NSObject {
/// - parameter after: The number of seconds before this emit times out if an ack hasn't been received. /// - parameter after: The number of seconds before this emit times out if an ack hasn't been received.
/// - parameter callback: The callback called when an ack is received, or when a timeout happens. /// - parameter callback: The callback called when an ack is received, or when a timeout happens.
/// To check for timeout, use `SocketAckStatus`'s `noAck` case. /// To check for timeout, use `SocketAckStatus`'s `noAck` case.
@objc
public func timingOut(after seconds: Double, callback: @escaping AckCallback) { public func timingOut(after seconds: Double, callback: @escaping AckCallback) {
guard let socket = self.socket, ackNumber != -1 else { return } guard let socket = self.socket, ackNumber != -1 else { return }

View File

@ -29,9 +29,11 @@ public final class SocketAnyEvent : NSObject {
// MARK: Properties // MARK: Properties
/// The event name. /// The event name.
@objc
public let event: String public let event: String
/// The data items for this event. /// The data items for this event.
@objc
public let items: [Any]? public let items: [Any]?
/// The description of this event. /// The description of this event.

View File

@ -36,9 +36,11 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
private static let logType = "SocketIOClient" private static let logType = "SocketIOClient"
/// The engine for this client. /// The engine for this client.
@objc
public private(set) var engine: SocketEngineSpec? public private(set) var engine: SocketEngineSpec?
/// The status of this client. /// The status of this client.
@objc
public private(set) var status = SocketIOClientStatus.notConnected { public private(set) var status = SocketIOClientStatus.notConnected {
didSet { didSet {
switch status { switch status {
@ -54,25 +56,31 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
} }
/// If `true` then every time `connect` is called, a new engine will be created. /// If `true` then every time `connect` is called, a new engine will be created.
@objc
public var forceNew = false public var forceNew = false
/// The queue that all interaction with the client should occur on. This is the queue that event handlers are /// The queue that all interaction with the client should occur on. This is the queue that event handlers are
/// called on. /// called on.
@objc
public var handleQueue = DispatchQueue.main public var handleQueue = DispatchQueue.main
/// The namespace for this client. /// The namespace for this client.
@objc
public var nsp = "/" public var nsp = "/"
/// The configuration for this client. /// The configuration for this client.
public var config: SocketIOClientConfiguration public var config: SocketIOClientConfiguration
/// If `true`, this client will try and reconnect on any disconnects. /// If `true`, this client will try and reconnect on any disconnects.
@objc
public var reconnects = true public var reconnects = true
/// The number of seconds to wait before attempting to reconnect. /// The number of seconds to wait before attempting to reconnect.
@objc
public var reconnectWait = 10 public var reconnectWait = 10
/// The session id of this client. /// The session id of this client.
@objc
public var sid: String? { public var sid: String? {
return engine?.sid return engine?.sid
} }
@ -81,6 +89,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// ///
/// If changed after calling `init`, `forceNew` must be set to `true`, or it will only connect to the url set in the /// If changed after calling `init`, `forceNew` must be set to `true`, or it will only connect to the url set in the
/// init. /// init.
@objc
public var socketURL: URL public var socketURL: URL
var ackHandlers = SocketAckManager() var ackHandlers = SocketAckManager()
@ -141,6 +150,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// ///
/// - parameter socketURL: The url of the socket.io server. /// - parameter socketURL: The url of the socket.io server.
/// - parameter config: The config for this socket. /// - parameter config: The config for this socket.
@objc
public convenience init(socketURL: NSURL, config: NSDictionary?) { public convenience init(socketURL: NSURL, config: NSDictionary?) {
self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? []) self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? [])
} }
@ -153,7 +163,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
// MARK: Methods // MARK: Methods
private func addEngine() { private func addEngine() {
DefaultSocketLogger.Logger.log("Adding engine", type: SocketIOClient.logType, args: "") DefaultSocketLogger.Logger.log("Adding engine", type: SocketIOClient.logType)
engine?.engineQueue.sync { engine?.engineQueue.sync {
self.engine?.client = nil self.engine?.client = nil
@ -163,6 +173,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
} }
/// Connect to the server. /// Connect to the server.
@objc
open func connect() { open func connect() {
connect(timeoutAfter: 0, withHandler: nil) connect(timeoutAfter: 0, withHandler: nil)
} }
@ -172,6 +183,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - parameter timeoutAfter: The number of seconds after which if we are not connected we assume the connection /// - parameter timeoutAfter: The number of seconds after which if we are not connected we assume the connection
/// has failed. Pass 0 to never timeout. /// has failed. Pass 0 to never timeout.
/// - parameter withHandler: The handler to call when the client fails to connect. /// - parameter withHandler: The handler to call when the client fails to connect.
@objc
open func connect(timeoutAfter: Double, withHandler handler: (() -> ())?) { open func connect(timeoutAfter: Double, withHandler handler: (() -> ())?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)") assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
@ -218,7 +230,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
func didDisconnect(reason: String) { func didDisconnect(reason: String) {
guard status != .disconnected else { return } guard status != .disconnected else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: SocketIOClient.logType, args: reason) DefaultSocketLogger.Logger.log("Disconnected: \(reason)", type: SocketIOClient.logType)
reconnecting = false reconnecting = false
status = .disconnected status = .disconnected
@ -229,6 +241,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
} }
/// Disconnects the socket. /// Disconnects the socket.
@objc
open func disconnect() { open func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: SocketIOClient.logType) DefaultSocketLogger.Logger.log("Closing socket", type: SocketIOClient.logType)
@ -257,6 +270,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// ///
/// - parameter event: The event to send. /// - parameter event: The event to send.
/// - parameter with: The items to send with this event. May be left out. /// - parameter with: The items to send with this event. May be left out.
@objc
open func emit(_ event: String, with items: [Any]) { open func emit(_ event: String, with items: [Any]) {
guard status == .connected else { guard status == .connected else {
handleClientEvent(.error, data: ["Tried emitting \(event) when not connected"]) handleClientEvent(.error, data: ["Tried emitting \(event) when not connected"])
@ -314,6 +328,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - parameter event: The event to send. /// - parameter event: The event to send.
/// - parameter with: The items to send with this event. Use `[]` to send nothing. /// - parameter with: The items to send with this event. Use `[]` to send nothing.
/// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent. /// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent.
@objc
open func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback { open func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback {
return createOnAck([event] + items) return createOnAck([event] + items)
} }
@ -327,7 +342,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false) let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: SocketIOClient.logType, args: str) DefaultSocketLogger.Logger.log("Emitting: \(str)", type: SocketIOClient.logType)
engine?.send(str, withData: packet.binary) engine?.send(str, withData: packet.binary)
} }
@ -339,7 +354,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
let packet = SocketPacket.packetFromEmit(items, id: ack, nsp: nsp, ack: true) let packet = SocketPacket.packetFromEmit(items, id: ack, nsp: nsp, ack: true)
let str = packet.packetString let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: SocketIOClient.logType, args: str) DefaultSocketLogger.Logger.log("Emitting Ack: \(str)", type: SocketIOClient.logType)
engine?.send(str, withData: packet.binary) engine?.send(str, withData: packet.binary)
} }
@ -378,7 +393,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
} }
private func _engineDidError(reason: String) { private func _engineDidError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: SocketIOClient.logType, args: reason) DefaultSocketLogger.Logger.error("\(reason)", type: SocketIOClient.logType)
handleClientEvent(.error, data: [reason]) handleClientEvent(.error, data: [reason])
} }
@ -394,7 +409,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
func handleAck(_ ack: Int, data: [Any]) { func handleAck(_ ack: Int, data: [Any]) {
guard status == .connected else { return } guard status == .connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: SocketIOClient.logType, args: ack, data) DefaultSocketLogger.Logger.log("Handling ack: \(ack) with data: \(data)", type: SocketIOClient.logType)
ackHandlers.executeAck(ack, with: data, onQueue: handleQueue) ackHandlers.executeAck(ack, with: data, onQueue: handleQueue)
} }
@ -405,11 +420,11 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - parameter data: the data associated with this event. /// - parameter data: the data associated with this event.
/// - parameter isInternalMessage: If `true` event handlers for this event will be called regardless of status. /// - parameter isInternalMessage: If `true` event handlers for this event will be called regardless of status.
/// - parameter withAck: The ack number for this event. May be left out. /// - parameter withAck: The ack number for this event. May be left out.
@objc
open func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) { open func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .connected || isInternalMessage else { return } guard status == .connected || isInternalMessage else { return }
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: SocketIOClient.logType, DefaultSocketLogger.Logger.log("Handling event: \(event) with data: \(data)", type: SocketIOClient.logType)
args: event, data)
anyHandler?(SocketAnyEvent(event: event, items: data)) anyHandler?(SocketAnyEvent(event: event, items: data))
@ -423,6 +438,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
} }
/// Leaves nsp and goes back to the default namespace. /// Leaves nsp and goes back to the default namespace.
@objc
open func leaveNamespace() { open func leaveNamespace() {
if nsp != "/" { if nsp != "/" {
engine?.send("1\(nsp)", withData: []) engine?.send("1\(nsp)", withData: [])
@ -435,6 +451,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// **Do not use this to join the default namespace.** Instead call `leaveNamespace`. /// **Do not use this to join the default namespace.** Instead call `leaveNamespace`.
/// ///
/// - parameter namespace: The namespace to join. /// - parameter namespace: The namespace to join.
@objc
open func joinNamespace(_ namespace: String) { open func joinNamespace(_ namespace: String) {
nsp = namespace nsp = namespace
@ -458,8 +475,9 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// If you wish to remove a specific event, call the `off(id:)` with the UUID received from its `on` call. /// If you wish to remove a specific event, call the `off(id:)` with the UUID received from its `on` call.
/// ///
/// - parameter event: The event to remove handlers for. /// - parameter event: The event to remove handlers for.
@objc
open func off(_ event: String) { open func off(_ event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: SocketIOClient.logType, args: event) DefaultSocketLogger.Logger.log("Removing handler for event: \(event)", type: SocketIOClient.logType)
handlers = handlers.filter({ $0.event != event }) handlers = handlers.filter({ $0.event != event })
} }
@ -469,8 +487,9 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// If you want to remove all events for an event, call the off `off(_:)` method with the event name. /// If you want to remove all events for an event, call the off `off(_:)` method with the event name.
/// ///
/// - parameter id: The UUID of the handler you wish to remove. /// - parameter id: The UUID of the handler you wish to remove.
@objc
open func off(id: UUID) { open func off(id: UUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: SocketIOClient.logType, args: id) DefaultSocketLogger.Logger.log("Removing handler with id: \(id)", type: SocketIOClient.logType)
handlers = handlers.filter({ $0.id != id }) handlers = handlers.filter({ $0.id != id })
} }
@ -480,9 +499,10 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - parameter event: The event name for this handler. /// - parameter event: The event name for this handler.
/// - parameter callback: The callback that will execute when this event is received. /// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it. /// - returns: A unique id for the handler that can be used to remove it.
@objc
@discardableResult @discardableResult
open func on(_ event: String, callback: @escaping NormalCallback) -> UUID { open func on(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: SocketIOClient.logType, args: event) DefaultSocketLogger.Logger.log("Adding handler for event: \(event)", type: SocketIOClient.logType)
let handler = SocketEventHandler(event: event, id: UUID(), callback: callback) let handler = SocketEventHandler(event: event, id: UUID(), callback: callback)
handlers.append(handler) handlers.append(handler)
@ -505,7 +525,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - returns: A unique id for the handler that can be used to remove it. /// - returns: A unique id for the handler that can be used to remove it.
@discardableResult @discardableResult
open func on(clientEvent event: SocketClientEvent, callback: @escaping NormalCallback) -> UUID { open func on(clientEvent event: SocketClientEvent, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: SocketIOClient.logType, args: event) DefaultSocketLogger.Logger.log("Adding handler for event: \(event)", type: SocketIOClient.logType)
let handler = SocketEventHandler(event: event.rawValue, id: UUID(), callback: callback) let handler = SocketEventHandler(event: event.rawValue, id: UUID(), callback: callback)
handlers.append(handler) handlers.append(handler)
@ -528,9 +548,10 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// - parameter event: The event name for this handler. /// - parameter event: The event name for this handler.
/// - parameter callback: The callback that will execute when this event is received. /// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it. /// - returns: A unique id for the handler that can be used to remove it.
@objc
@discardableResult @discardableResult
open func once(_ event: String, callback: @escaping NormalCallback) -> UUID { open func once(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: SocketIOClient.logType, args: event) DefaultSocketLogger.Logger.log("Adding once handler for event: \(event)", type: SocketIOClient.logType)
let id = UUID() let id = UUID()
@ -548,6 +569,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// Adds a handler that will be called on every event. /// Adds a handler that will be called on every event.
/// ///
/// - parameter handler: The callback that will execute whenever an event is received. /// - parameter handler: The callback that will execute whenever an event is received.
@objc
open func onAny(_ handler: @escaping (SocketAnyEvent) -> ()) { open func onAny(_ handler: @escaping (SocketAnyEvent) -> ()) {
anyHandler = handler anyHandler = handler
} }
@ -556,7 +578,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// ///
/// - parameter msg: The message that needs parsing. /// - parameter msg: The message that needs parsing.
public func parseEngineMessage(_ msg: String) { public func parseEngineMessage(_ msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: SocketIOClient.logType, args: msg) DefaultSocketLogger.Logger.log("Should parse message: \(msg)", type: SocketIOClient.logType)
handleQueue.async { self.parseSocketMessage(msg) } handleQueue.async { self.parseSocketMessage(msg) }
} }
@ -571,6 +593,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// Tries to reconnect to the server. /// Tries to reconnect to the server.
/// ///
/// This will cause a `disconnect` event to be emitted, as well as an `reconnectAttempt` event. /// This will cause a `disconnect` event to be emitted, as well as an `reconnectAttempt` event.
@objc
open func reconnect() { open func reconnect() {
guard !reconnecting else { return } guard !reconnecting else { return }
@ -579,6 +602,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So
/// Removes all handlers. /// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles. /// Can be used after disconnecting to break any potential remaining retain cycles.
@objc
open func removeAllHandlers() { open func removeAllHandlers() {
handlers.removeAll(keepingCapacity: false) handlers.removeAll(keepingCapacity: false)
} }

View File

@ -40,7 +40,7 @@ protocol SocketIOClientSpec : class {
extension SocketIOClientSpec { extension SocketIOClientSpec {
func didError(reason: String) { func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason) DefaultSocketLogger.Logger.error("\(reason)", type: "SocketIOClient")
handleClientEvent(.error, data: [reason]) handleClientEvent(.error, data: [reason])
} }

View File

@ -206,7 +206,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
private func checkAndHandleEngineError(_ msg: String) { private func checkAndHandleEngineError(_ msg: String) {
do { do {
let dict = try msg.toNSDictionary() let dict = try msg.toDictionary()
guard let error = dict["message"] as? String else { return } guard let error = dict["message"] as? String else { return }
/* /*
@ -223,7 +223,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
private func handleBase64(message: String) { private func handleBase64(message: String) {
// binary in base64 string // binary in base64 string
let noPrefix = message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex] let noPrefix = String(message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex])
if let data = Data(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) { if let data = Data(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) {
client?.parseEngineBinaryData(data) client?.parseEngineBinaryData(data)
@ -255,7 +255,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
disconnect(reason: "reconnect") disconnect(reason: "reconnect")
} }
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: SocketEngine.logType, args: url) DefaultSocketLogger.Logger.log("Starting engine. Server: \(url)", type: SocketEngine.logType)
DefaultSocketLogger.Logger.log("Handshaking", type: SocketEngine.logType) DefaultSocketLogger.Logger.log("Handshaking", type: SocketEngine.logType)
resetEngine() resetEngine()
@ -336,7 +336,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
/// Called when an error happens during execution. Causes a disconnection. /// Called when an error happens during execution. Causes a disconnection.
public func didError(reason: String) { public func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: SocketEngine.logType, args: reason) DefaultSocketLogger.Logger.error("\(reason)", type: SocketEngine.logType)
client?.engineDidError(reason: reason) client?.engineDidError(reason: reason)
disconnect(reason: reason) disconnect(reason: reason)
} }
@ -435,7 +435,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
} }
private func handleOpen(openData: String) { private func handleOpen(openData: String) {
guard let json = try? openData.toNSDictionary() else { guard let json = try? openData.toDictionary() else {
didError(reason: "Error parsing open packet") didError(reason: "Error parsing open packet")
return return
@ -490,7 +490,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
/// ///
/// - parameter data: The data to parse. /// - parameter data: The data to parse.
public func parseEngineData(_ data: Data) { public func parseEngineData(_ data: Data) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: SocketEngine.logType, args: data) DefaultSocketLogger.Logger.log("Got binary data: \(data)", type: SocketEngine.logType)
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex)) client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
} }
@ -501,7 +501,7 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
/// - parameter fromPolling: Whether this message is from long-polling. /// - parameter fromPolling: Whether this message is from long-polling.
/// If `true` we might have to fix utf8 encoding. /// If `true` we might have to fix utf8 encoding.
public func parseEngineMessage(_ message: String) { public func parseEngineMessage(_ message: String) {
DefaultSocketLogger.Logger.log("Got message: %@", type: SocketEngine.logType, args: message) DefaultSocketLogger.Logger.log("Got message: \(message)", type: SocketEngine.logType)
let reader = SocketStringReader(message: message) let reader = SocketStringReader(message: message)
@ -588,12 +588,12 @@ public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePoll
guard self.connected else { return } guard self.connected else { return }
if self.websocket { if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@", DefaultSocketLogger.Logger.log("Writing ws: \(msg) has data: \(data.count != 0)",
type: SocketEngine.logType, args: msg, data.count != 0) type: SocketEngine.logType)
self.sendWebSocketMessage(msg, withType: type, withData: data) self.sendWebSocketMessage(msg, withType: type, withData: data)
} else if !self.probing { } else if !self.probing {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@", DefaultSocketLogger.Logger.log("Writing poll: \(msg) has data: \(data.count != 0)",
type: SocketEngine.logType, args: msg, data.count != 0) type: SocketEngine.logType)
self.sendPollMessage(msg, withType: type, withData: data) self.sendPollMessage(msg, withType: type, withData: data)
} else { } else {
self.probeWait.append((msg, type, data)) self.probeWait.append((msg, type, data))

View File

@ -80,7 +80,7 @@ extension SocketEnginePollable {
postStr += "\(packet.utf16.count):\(packet)" postStr += "\(packet.utf16.count):\(packet)"
} }
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr) DefaultSocketLogger.Logger.log("Created POST string: \(postStr)", type: "SocketEnginePolling")
var req = URLRequest(url: urlPollingWithSid) var req = URLRequest(url: urlPollingWithSid)
let postData = postStr.data(using: .utf8, allowLossyConversion: false)! let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
@ -110,8 +110,7 @@ extension SocketEnginePollable {
func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> ()) { func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> ()) {
guard polling && !closed && !invalidated && !fastUpgrade else { return } guard polling && !closed && !invalidated && !fastUpgrade else { return }
DefaultSocketLogger.Logger.log("Doing polling %@ %@", type: "SocketEnginePolling", DefaultSocketLogger.Logger.log("Doing polling \(req.httpMethod ?? "") \(req)", type: "SocketEnginePolling")
args: req.httpMethod ?? "", req)
session?.dataTask(with: req, completionHandler: callback).resume() session?.dataTask(with: req, completionHandler: callback).resume()
} }
@ -187,7 +186,7 @@ extension SocketEnginePollable {
func parsePollingMessage(_ str: String) { func parsePollingMessage(_ str: String) {
guard str.characters.count != 1 else { return } guard str.characters.count != 1 else { return }
DefaultSocketLogger.Logger.log("Got poll message: %@", type: "SocketEnginePolling", args: str) DefaultSocketLogger.Logger.log("Got poll message: \(str)", type: "SocketEnginePolling")
var reader = SocketStringReader(message: str) var reader = SocketStringReader(message: str)
@ -209,7 +208,7 @@ extension SocketEnginePollable {
/// - parameter withType: The type of message to send. /// - parameter withType: The type of message to send.
/// - parameter withData: The data associated with this message. /// - parameter withData: The data associated with this message.
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data]) { public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue) DefaultSocketLogger.Logger.log("Sending poll: \(message) as type: \(type.rawValue)", type: "SocketEnginePolling")
postWait.append(String(type.rawValue) + message) postWait.append(String(type.rawValue) + message)

View File

@ -161,12 +161,7 @@ extension SocketEngineSpec {
func createBinaryDataForSend(using data: Data) -> Either<Data, String> { func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
if websocket { if websocket {
var byteArray = [UInt8](repeating: 0x4, count: 1) return .left(Data(bytes: [0x4]) + data)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.append(data)
return .left(mutData as Data)
} else { } else {
return .right("b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))) return .right("b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)))
} }

View File

@ -54,7 +54,7 @@ extension SocketEngineWebsocket {
/// - parameter withType: The type of message to send. /// - parameter withType: The type of message to send.
/// - parameter withData: The data associated with this message. /// - parameter withData: The data associated with this message.
public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) { public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue) DefaultSocketLogger.Logger.log("Sending ws: \(str) as type: \(type.rawValue)", type: "SocketEngineWebSocket")
ws?.write(string: "\(type.rawValue)\(str)") ws?.write(string: "\(type.rawValue)\(str)")

View File

@ -63,7 +63,7 @@ extension SocketParsable where Self: SocketIOClientSpec {
case .error: case .error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id) handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default: default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description) DefaultSocketLogger.Logger.log("Got invalid packet: \(pack.description)", type: "SocketParser")
} }
} }
@ -137,16 +137,16 @@ extension SocketParsable where Self: SocketIOClientSpec {
func parseSocketMessage(_ message: String) { func parseSocketMessage(_ message: String) {
guard !message.isEmpty else { return } guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message) DefaultSocketLogger.Logger.log("Parsing \(message)", type: "SocketParser")
do { do {
let packet = try parseString(message) let packet = try parseString(message)
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: packet.description) DefaultSocketLogger.Logger.log("Decoded packet as: \(packet.description)", type: "SocketParser")
handlePacket(packet) handlePacket(packet)
} catch { } catch {
DefaultSocketLogger.Logger.error("\(error): %@", type: "SocketParser", args: message) DefaultSocketLogger.Logger.error("\(error): \(message)", type: "SocketParser")
} }
} }

View File

@ -47,6 +47,7 @@ open class SocketClientManager : NSObject {
// MARK: Properties. // MARK: Properties.
/// The shared manager. /// The shared manager.
@objc
open static let sharedManager = SocketClientManager() open static let sharedManager = SocketClientManager()
private var sockets = [String: SocketIOClient]() private var sockets = [String: SocketIOClient]()
@ -70,6 +71,7 @@ open class SocketClientManager : NSObject {
/// ///
/// - parameter socket: The socket to add. /// - parameter socket: The socket to add.
/// - parameter labeledAs: The label for this socket. /// - parameter labeledAs: The label for this socket.
@objc
open func addSocket(_ socket: SocketIOClient, labeledAs label: String) { open func addSocket(_ socket: SocketIOClient, labeledAs label: String) {
sockets[label] = socket sockets[label] = socket
} }
@ -78,6 +80,7 @@ open class SocketClientManager : NSObject {
/// ///
/// - parameter withLabel: The label of the socket to remove. /// - parameter withLabel: The label of the socket to remove.
/// - returns: The socket for the given label, if one was present. /// - returns: The socket for the given label, if one was present.
@objc
@discardableResult @discardableResult
open func removeSocket(withLabel label: String) -> SocketIOClient? { open func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValue(forKey: label) return sockets.removeValue(forKey: label)
@ -87,6 +90,7 @@ open class SocketClientManager : NSObject {
/// ///
/// - parameter socket: The socket to remove. /// - parameter socket: The socket to remove.
/// - returns: The socket if it was in the manager. /// - returns: The socket if it was in the manager.
@objc
@discardableResult @discardableResult
open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? { open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? {
var returnSocket: SocketIOClient? var returnSocket: SocketIOClient?
@ -99,6 +103,7 @@ open class SocketClientManager : NSObject {
} }
/// Removes all the sockets in the manager. /// Removes all the sockets in the manager.
@objc
open func removeSockets() { open func removeSockets() {
sockets.removeAll() sockets.removeAll()
} }

View File

@ -111,9 +111,9 @@ extension String {
return array return array
} }
func toNSDictionary() throws -> NSDictionary { func toDictionary() throws -> [String: Any] {
guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] } guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] }
guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? NSDictionary else { guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? [String: Any] else {
throw JSONError.notNSDictionary throw JSONError.notNSDictionary
} }

View File

@ -38,34 +38,31 @@ public protocol SocketLogger : class {
/// - parameter message: The message being logged. Can include `%@` that will be replaced with `args` /// - parameter message: The message being logged. Can include `%@` that will be replaced with `args`
/// - parameter type: The type of entity that called for logging. /// - parameter type: The type of entity that called for logging.
/// - parameter args: Any args that should be inserted into the message. May be left out. /// - parameter args: Any args that should be inserted into the message. May be left out.
func log(_ message: String, type: String, args: Any...) func log(_ message: @autoclosure () -> String, type: String)
/// Error Messages /// Error Messages
/// ///
/// - parameter message: The message being logged. Can include `%@` that will be replaced with `args` /// - parameter message: The message being logged. Can include `%@` that will be replaced with `args`
/// - parameter type: The type of entity that called for logging. /// - parameter type: The type of entity that called for logging.
/// - parameter args: Any args that should be inserted into the message. May be left out. /// - parameter args: Any args that should be inserted into the message. May be left out.
func error(_ message: String, type: String, args: Any...) func error(_ message: @autoclosure () -> String, type: String)
} }
public extension SocketLogger { public extension SocketLogger {
/// Default implementation. /// Default implementation.
func log(_ message: String, type: String, args: Any...) { func log(_ message: @autoclosure () -> String, type: String) {
abstractLog("LOG", message: message, type: type, args: args) abstractLog("LOG", message: message, type: type)
} }
/// Default implementation. /// Default implementation.
func error(_ message: String, type: String, args: Any...) { func error(_ message: @autoclosure () -> String, type: String) {
abstractLog("ERROR", message: message, type: type, args: args) abstractLog("ERROR", message: message, type: type)
} }
private func abstractLog(_ logType: String, message: String, type: String, args: [Any]) { private func abstractLog(_ logType: String, message: @autoclosure () -> String, type: String) {
guard log else { return } guard log else { return }
let newArgs = args.map({arg -> CVarArg in String(describing: arg)}) NSLog("\(logType) \(type): %@", message())
let messageFormat = String(format: message, arguments: newArgs)
NSLog("\(logType) \(type): %@", messageFormat)
} }
} }