Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44c5591646 | ||
|
|
8e0d03b28c | ||
|
|
7b1f72852f | ||
|
|
97d4f3f527 | ||
|
|
d94a1901ca | ||
|
|
fff2f29c55 | ||
|
|
57d1f3c4b4 | ||
|
|
499c0d6824 | ||
|
|
85cf6c48b1 | ||
|
|
5848516c4e | ||
|
|
238d3cb338 | ||
|
|
275c873880 | ||
|
|
2ccaa4351a | ||
|
|
c642017f4b | ||
|
|
7b11e7c3e0 | ||
|
|
6e5b95be31 | ||
|
|
ccad13a1ed | ||
|
|
bb26ae8637 | ||
|
|
b9fd6c9d5b | ||
|
|
f001b8340c | ||
|
|
9b67549d25 | ||
|
|
e2f89d82e4 | ||
|
|
9c1a3edeb9 | ||
|
|
04d49fe7cb | ||
|
|
c74858fd5d | ||
|
|
0acb7421cc | ||
|
|
57b252fa7d | ||
|
|
87e12fd284 | ||
|
|
0470647d87 | ||
|
|
80a734e95f | ||
|
|
c26adae13c | ||
|
|
76375bbcf3 | ||
|
|
6199c2f914 | ||
|
|
e0c794cb9f | ||
|
|
db63aa63c2 | ||
|
|
9aec259d67 | ||
|
|
6e21fba469 | ||
|
|
38e08f17a2 | ||
|
|
71c78e1e12 | ||
|
|
b35004ef60 | ||
|
|
cf14eb27a3 | ||
|
|
0de8a65ff4 | ||
|
|
fe21fcc7e1 | ||
|
|
4be7bb0079 | ||
|
|
da5977ac31 | ||
|
|
bbb383da58 | ||
|
|
c818ed2c10 | ||
|
|
6e54ac4534 | ||
|
|
a87214cf06 | ||
|
|
8c405cee88 | ||
|
|
0b6cece96b | ||
|
|
9633bea018 | ||
|
|
d808ae18d2 | ||
|
|
f6dabf8f8e | ||
|
|
47fd0e386f | ||
|
|
9deb5a06a6 | ||
|
|
8f27b0d021 | ||
|
|
e137e66592 | ||
|
|
bba966a125 | ||
|
|
0579e7ec19 | ||
|
|
aee0382cbc | ||
|
|
9abf2e77e0 | ||
|
|
0dd3def2e4 | ||
|
|
c5d70b4888 | ||
|
|
ee38630468 | ||
|
|
5a65efe526 | ||
|
|
02971e14c2 | ||
|
|
ea7e60cde2 | ||
|
|
83cee796d8 | ||
|
|
86bd271a9f | ||
|
|
6e31f54e88 | ||
|
|
b97574e28a | ||
|
|
ab56b58b2d | ||
|
|
8e2f478989 | ||
|
|
c99f9a6b97 | ||
|
|
45b5852e50 | ||
|
|
c608bf8286 | ||
|
|
6c6084705e | ||
|
|
885965c5bc | ||
|
|
ac228ccede | ||
|
|
7bc8cd01e8 | ||
|
|
b9e05286a2 | ||
|
|
a5db43b834 | ||
|
|
7382030dff | ||
|
|
40ac53844d | ||
|
|
7f443faf92 | ||
|
|
a6c700230d | ||
|
|
aa368f92cf | ||
|
|
28ae7a8240 | ||
|
|
e07ed93c0b | ||
|
|
17fb142083 | ||
|
|
66674aae78 | ||
|
|
395dc48287 | ||
|
|
1648a51b6f | ||
|
|
ad7043c918 | ||
|
|
48672d8df3 | ||
|
|
d657538214 | ||
|
|
a231104c15 | ||
|
|
ab8de6932c | ||
|
|
c101a04845 | ||
|
|
3d06b7dbad | ||
|
|
f57786ad5b | ||
|
|
7ff1d327de | ||
|
|
99e2da235a | ||
|
|
a20a0f14f3 | ||
|
|
0e478085a3 | ||
|
|
61eda5971e | ||
|
|
32e1f55394 | ||
|
|
a88a859750 | ||
|
|
aaefdd0a2e | ||
|
|
4c7a09cc8e | ||
|
|
90c7c9aadc | ||
|
|
84499d4c21 | ||
|
|
bfe54f8df7 | ||
|
|
18a227e591 | ||
|
|
6d49c37fb8 | ||
|
|
a0c213364d | ||
|
|
3c79bd0a75 | ||
|
|
a11533b61f | ||
|
|
8acd32324e | ||
|
|
b65dfec6b0 | ||
|
|
1e07070798 | ||
|
|
927ab155e3 | ||
|
|
de20099c07 | ||
|
|
877db516c2 | ||
|
|
7573355731 | ||
|
|
f3b4c0eba3 | ||
|
|
d2f39b163a | ||
|
|
b8ab80bdf1 | ||
|
|
66455f3e1b | ||
|
|
5d867f4f65 | ||
|
|
1ad87bdb0d | ||
|
|
14dc5957fc | ||
|
|
e99030846f | ||
|
|
3f8941d35b | ||
|
|
3025911502 | ||
|
|
3791b9c112 | ||
|
|
39135c089b | ||
|
|
bd5e2db98a | ||
|
|
4531d2e1a1 | ||
|
|
5772f8fb4f | ||
|
|
b336f0e267 | ||
|
|
d647c53122 | ||
|
|
288c04e629 | ||
|
|
a5d40c4479 | ||
|
|
c0afc006e3 | ||
|
|
fe0d5d835f | ||
|
|
ded625aaef | ||
|
|
54e0b6c189 | ||
|
|
72ed7d4be8 | ||
|
|
b9c01ce614 | ||
|
|
faaa0473d9 | ||
|
|
195f04c982 |
No files matched your search
@@ -2,6 +2,8 @@
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
*.xcodeproj
|
||||
.build/*
|
||||
Packages/*
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
+7
-4
@@ -2,9 +2,12 @@ language: objective-c
|
||||
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
|
||||
xcode_scheme: SocketIO-iOS
|
||||
osx_image: xcode7
|
||||
script: xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-iOS -sdk iphonesimulator build test CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
|
||||
before_install:
|
||||
install: cd Socket.IO-Test-Server/ && npm install && cd .. && node Socket.IO-Test-Server/main.js &
|
||||
before_install:
|
||||
- cd Socket.IO-Test-Server/
|
||||
- npm install
|
||||
- cd ..
|
||||
install: node Socket.IO-Test-Server/main.js &
|
||||
script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
|
||||
cache:
|
||||
directories:
|
||||
- Socket.IO-Test-Server/node_modules
|
||||
- Socket.IO-Test-Server/node_modules
|
||||
@@ -0,0 +1,5 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SocketIOClientSwift"
|
||||
)
|
||||
@@ -5,7 +5,7 @@ Socket.IO-client for iOS/OS X.
|
||||
|
||||
##Example
|
||||
```swift
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080")
|
||||
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
|
||||
|
||||
socket.on("connect") {data, ack in
|
||||
print("socket connected")
|
||||
@@ -17,7 +17,7 @@ socket.on("currentAmount") {data, ack in
|
||||
socket.emit("update", ["amount": cur + 2.50])
|
||||
}
|
||||
|
||||
ack?.with("Got your currentAmount", "dude")
|
||||
ack.with("Got your currentAmount", "dude")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ socket.connect()
|
||||
|
||||
##Objective-C Example
|
||||
```objective-c
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" opts:nil];
|
||||
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
|
||||
|
||||
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
|
||||
NSLog(@"socket connected");
|
||||
@@ -60,20 +60,20 @@ If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer m
|
||||
|
||||
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
|
||||
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the Source folder into your Xcode project. (Make sure you add the files to your target(s))
|
||||
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
|
||||
|
||||
Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 3.1.4 # Or latest version
|
||||
github "socketio/socket.io-client-swift" ~> 4.1.6 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the SocketIOClientSwift folder into your Xcode project. (Make sure you add the files to your target(s))
|
||||
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
|
||||
|
||||
CocoaPods 0.36.0 or later (iOS 8+)
|
||||
------------------
|
||||
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
|
||||
@@ -83,7 +83,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 3.1.4' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 4.1.6' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -100,36 +100,59 @@ import Socket_IO_Client_Swift
|
||||
```
|
||||
|
||||
Objective-C:
|
||||
|
||||
```Objective-C
|
||||
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
|
||||
```
|
||||
|
||||
CocoaSeeds
|
||||
-----------------
|
||||
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v4.1.6", :files => "SocketIOClientSwift/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
|
||||
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
`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.
|
||||
`init(var socketURL: String, options: Set<SocketIOClientOption> = [])` - 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.
|
||||
|
||||
`convenience init(socketURL: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
|
||||
|
||||
Options
|
||||
-------
|
||||
- `connectParams: [String: AnyObject]?` - Dictionary whose contents will be passed with the connection.
|
||||
- `reconnects: Bool` Default is `true`
|
||||
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
|
||||
- `reconnectWait: Int` Default is `10`
|
||||
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
|
||||
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
|
||||
- `nsp: String` Default is `"/"`. Connects to a namespace.
|
||||
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
- `log: Bool` If `true` socket will log debug messages. Default is false.
|
||||
- `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.
|
||||
- `sessionDelegate: NSURLSessionDelegate` Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
|
||||
- `path: String` - If the server uses a custom path. ex: `"/swift"`. Default is `""`
|
||||
- `extraHeaders: [String: String]?` - Adds custom headers to the initial request. Default is nil.
|
||||
- `handleQueue: dispatch_queue_t` - The dispatch queue that handlers are run on. Default is the main queue.
|
||||
All options are a case of SocketIOClientOption. To get the Objective-C Option, convert the name to lowerCamelCase.
|
||||
|
||||
```swift
|
||||
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
|
||||
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
|
||||
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
|
||||
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
|
||||
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
|
||||
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
|
||||
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
|
||||
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
|
||||
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
|
||||
case Log(Bool) // If `true` socket will log debug messages. Default is false.
|
||||
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
|
||||
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
|
||||
case Path(String) // If the server uses a custom path. ex: `"/swift"`. Default is `""`
|
||||
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
|
||||
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
|
||||
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
|
||||
case Secure(Bool) // If the connection should use TLS. Default is false.
|
||||
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
|
||||
|
||||
```
|
||||
Methods
|
||||
-------
|
||||
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.
|
||||
2. `once(event: String, callback: NormalCallback)` - Adds a handler that will only be executed once.
|
||||
1. `on(event: String, callback: NormalCallback) -> NSUUID` - 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. Returns a unique id for the handler.
|
||||
2. `once(event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
|
||||
3. `onAny(callback:((event: String, items: AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
|
||||
4. `emit(event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
|
||||
5. `emit(event: String, withItems items: [AnyObject])` - `emit` for Objective-C
|
||||
@@ -141,6 +164,9 @@ Methods
|
||||
11. `reconnect()` - Causes the client to reconnect to the server.
|
||||
12. `joinNamespace()` - Causes the client to join nsp. Shouldn't need to be called unless you change nsp manually.
|
||||
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
|
||||
14. `off(event: String)` - Removes all event handlers for event.
|
||||
15. `off(id id: NSUUID)` - Removes the event that corresponds to id.
|
||||
16. `removeAllHandlers()` - Removes all handlers.
|
||||
|
||||
Client Events
|
||||
------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "3.1.4"
|
||||
s.version = "4.1.6"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -12,8 +12,9 @@ Pod::Spec.new do |s|
|
||||
s.author = { "Erik" => "nuclear.ace@gmail.com" }
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v3.1.4' }
|
||||
s.source_files = "SocketIOClientSwift/**/*.swift"
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v4.1.6' }
|
||||
s.source_files = "Source/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
end
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0710"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
|
||||
BuildableName = "SocketIO-tvOSTests.xctest"
|
||||
BlueprintName = "SocketIO-tvOSTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
|
||||
BuildableName = "SocketIO-tvOSTests.xctest"
|
||||
BlueprintName = "SocketIO-tvOSTests"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
|
||||
BuildableName = "SocketIO.framework"
|
||||
BlueprintName = "SocketIO-tvOS"
|
||||
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,139 @@
|
||||
//
|
||||
// SocketBasicPacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketBasicPacketTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
|
||||
func testEmpyEmit() {
|
||||
let expectedSendString = "2[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullEmit() {
|
||||
let expectedSendString = "2[\"test\",null]"
|
||||
let sendData = ["test", NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringEmit() {
|
||||
let expectedSendString = "2[\"test\",\"foo bar\"]"
|
||||
let sendData = ["test", "foo bar"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONEmit() {
|
||||
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testArrayEmit() {
|
||||
let expectedSendString = "2[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
|
||||
let sendData = ["test", ["hello", 1, ["test": "test"]]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryEmit() {
|
||||
let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryEmit() {
|
||||
let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = ["test", ["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data, data2])
|
||||
}
|
||||
|
||||
func testEmitWithAck() {
|
||||
let expectedSendString = "20[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testEmitDataWithAck() {
|
||||
let expectedSendString = "51-0[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
// Acks
|
||||
func testEmptyAck() {
|
||||
let expectedSendString = "30[]"
|
||||
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullAck() {
|
||||
let expectedSendString = "30[null]"
|
||||
let sendData = [NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringAck() {
|
||||
let expectedSendString = "30[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONAck() {
|
||||
let expectedSendString = "30[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryAck() {
|
||||
let expectedSendString = "61-0[{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = [data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryAck() {
|
||||
let expectedSendString = "62-0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = [["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//
|
||||
// SocketEngineTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/15/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketEngineTest: XCTestCase {
|
||||
var client: SocketIOClient!
|
||||
var engine: SocketEngine!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
client = SocketIOClient(socketURL: "")
|
||||
engine = SocketEngine(client: client, url: "", options: nil)
|
||||
|
||||
client.setTestable()
|
||||
}
|
||||
|
||||
func testBasicPollingMessage() {
|
||||
let expectation = expectationWithDescription("Basic polling test")
|
||||
client.on("blankTest") {data, ack in
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
engine.parsePollingMessage("15:42[\"blankTest\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testTwoPacketsInOnePollTest() {
|
||||
let finalExpectation = expectationWithDescription("Final packet in poll test")
|
||||
var gotBlank = false
|
||||
|
||||
client.on("blankTest") {data, ack in
|
||||
gotBlank = true
|
||||
}
|
||||
|
||||
client.on("stringTest") {data, ack in
|
||||
if let str = data[0] as? String where gotBlank {
|
||||
if str == "hello" {
|
||||
finalExpectation.fulfill()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
//
|
||||
// SocketIO_MacTests.swift
|
||||
// SocketIO-MacTests
|
||||
//
|
||||
// Created by Nacho Soto on 7/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import XCTest
|
||||
|
||||
class SocketIO_MacTests: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
// This is an example of a functional test case.
|
||||
XCTAssert(true, "Pass")
|
||||
}
|
||||
|
||||
func testPerformanceExample() {
|
||||
// This is an example of a performance test case.
|
||||
self.measureBlock() {
|
||||
// Put the code you want to measure the time of here.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//
|
||||
// SocketNamespacePacketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketNamespacePacketTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
|
||||
func testEmpyEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",null]"
|
||||
let sendData = ["test", NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",\"foo bar\"]"
|
||||
let sendData = ["test", "foo bar"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testArrayEmit() {
|
||||
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
|
||||
let sendData = ["test", ["hello", 1, ["test": "test"]]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryEmit() {
|
||||
let expectedSendString = "51-/swift,[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryEmit() {
|
||||
let expectedSendString = "52-/swift,[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = ["test", ["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data, data2])
|
||||
}
|
||||
|
||||
func testEmitWithAck() {
|
||||
let expectedSendString = "2/swift,0[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testEmitDataWithAck() {
|
||||
let expectedSendString = "51-/swift,0[\"test\",{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = ["test", data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
// Acks
|
||||
func testEmptyAck() {
|
||||
let expectedSendString = "3/swift,0[]"
|
||||
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testNullAck() {
|
||||
let expectedSendString = "3/swift,0[null]"
|
||||
let sendData = [NSNull()]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testStringAck() {
|
||||
let expectedSendString = "3/swift,0[\"test\"]"
|
||||
let sendData = ["test"]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testJSONAck() {
|
||||
let expectedSendString = "3/swift,0[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
|
||||
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
}
|
||||
|
||||
func testBinaryAck() {
|
||||
let expectedSendString = "61-/swift,0[{\"num\":0,\"_placeholder\":true}]"
|
||||
let sendData = [data]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data])
|
||||
}
|
||||
|
||||
func testMultipleBinaryAck() {
|
||||
let expectedSendString = "62-/swift,0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
|
||||
let sendData = [["data1": data, "data2": data2]]
|
||||
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
|
||||
|
||||
XCTAssertEqual(packet.packetString, expectedSendString)
|
||||
XCTAssertEqual(packet.binary, [data2, data])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//
|
||||
// SocketSideEffectTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/11/15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketSideEffectTest: XCTestCase {
|
||||
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
private var socket: SocketIOClient!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
socket = SocketIOClient(socketURL: "")
|
||||
socket.setTestable()
|
||||
}
|
||||
|
||||
func testInitialCurrentAck() {
|
||||
XCTAssertEqual(socket.currentAck, -1)
|
||||
}
|
||||
|
||||
func testFirstAck() {
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
XCTAssertEqual(socket.currentAck, 0)
|
||||
}
|
||||
|
||||
func testSecondAck() {
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
|
||||
|
||||
XCTAssertEqual(socket.currentAck, 1)
|
||||
}
|
||||
|
||||
func testHandleAck() {
|
||||
let expectation = expectationWithDescription("handled ack")
|
||||
socket.emitWithAck("test")(timeoutAfter: 0) {data in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("30[\"hello world\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleEvent() {
|
||||
let expectation = expectationWithDescription("handled event")
|
||||
socket.on("test") {data, ack in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleOnceEvent() {
|
||||
let expectation = expectationWithDescription("handled event")
|
||||
socket.once("test") {data, ack in
|
||||
XCTAssertEqual(data[0] as? String, "hello world")
|
||||
XCTAssertEqual(self.socket.testHandlers.count, 0)
|
||||
expectation.fulfill()
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testOffWithEvent() {
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 2)
|
||||
socket.off("test")
|
||||
XCTAssertEqual(socket.testHandlers.count, 0)
|
||||
}
|
||||
|
||||
func testOffWithId() {
|
||||
let handler = socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
socket.on("test") {data, ack in }
|
||||
XCTAssertEqual(socket.testHandlers.count, 2)
|
||||
socket.off(id: handler)
|
||||
XCTAssertEqual(socket.testHandlers.count, 1)
|
||||
}
|
||||
|
||||
func testHandleBinaryEvent() {
|
||||
let expectation = expectationWithDescription("handled binary event")
|
||||
socket.on("test") {data, ack in
|
||||
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData {
|
||||
XCTAssertEqual(data, self.data)
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
|
||||
socket.parseBinaryData(data)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
|
||||
func testHandleMultipleBinaryEvent() {
|
||||
let expectation = expectationWithDescription("handled multiple binary event")
|
||||
socket.on("test") {data, ack in
|
||||
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData,
|
||||
data2 = dict["test2"] as? NSData {
|
||||
XCTAssertEqual(data, self.data)
|
||||
XCTAssertEqual(data2, self.data2)
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
|
||||
socket.parseBinaryData(data)
|
||||
socket.parseBinaryData(data2)
|
||||
waitForExpectationsWithTimeout(3, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
//
|
||||
// AbstractSocketTest.swift
|
||||
// AbstractSocketTest.socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 02.08.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class AbstractSocketTest: XCTestCase {
|
||||
static let serverURL = "localhost:6979"
|
||||
static let TEST_TIMEOUT = 8.0
|
||||
static var socket:SocketIOClient!
|
||||
var testKind:TestKind?
|
||||
|
||||
|
||||
func openConnection() {
|
||||
guard AbstractSocketTest.socket.status == SocketIOClientStatus.NotConnected else {return}
|
||||
|
||||
weak var expection = self.expectationWithDescription("connect")
|
||||
XCTAssertTrue(AbstractSocketTest.socket.status == SocketIOClientStatus.NotConnected)
|
||||
AbstractSocketTest.socket.on("connect") {data, ack in
|
||||
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connected)
|
||||
XCTAssertFalse(AbstractSocketTest.socket.secure)
|
||||
if let expection = expection {
|
||||
expection.fulfill()
|
||||
}
|
||||
}
|
||||
AbstractSocketTest.socket.connect()
|
||||
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connecting)
|
||||
waitForExpectationsWithTimeout(AbstractSocketTest.TEST_TIMEOUT, handler: nil)
|
||||
}
|
||||
|
||||
func generateTestName(rawTestName:String) ->String {
|
||||
return rawTestName + testKind!.rawValue
|
||||
}
|
||||
|
||||
func checkConnectionStatus() {
|
||||
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connected)
|
||||
XCTAssertFalse(AbstractSocketTest.socket.secure)
|
||||
}
|
||||
|
||||
func socketMultipleEmit(testName:String, emitData:Array<AnyObject>, callback:NormalCallback){
|
||||
let finalTestname = generateTestName(testName)
|
||||
weak var expection = self.expectationWithDescription(finalTestname)
|
||||
func didGetEmit(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
callback(result, ack)
|
||||
if let expection = expection {
|
||||
expection.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
AbstractSocketTest.socket.emit(finalTestname, withItems: emitData)
|
||||
AbstractSocketTest.socket.on(finalTestname + "Return", callback: didGetEmit)
|
||||
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
|
||||
}
|
||||
|
||||
|
||||
func socketEmit(testName:String, emitData:AnyObject?, callback:NormalCallback){
|
||||
let finalTestname = generateTestName(testName)
|
||||
weak var expection = self.expectationWithDescription(finalTestname)
|
||||
func didGetEmit(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
callback(result, ack)
|
||||
if let expection = expection {
|
||||
expection.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
AbstractSocketTest.socket.on(finalTestname + "Return", callback: didGetEmit)
|
||||
if let emitData = emitData {
|
||||
AbstractSocketTest.socket.emit(finalTestname, emitData)
|
||||
} else {
|
||||
AbstractSocketTest.socket.emit(finalTestname)
|
||||
}
|
||||
|
||||
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
|
||||
}
|
||||
|
||||
|
||||
func socketAcknwoledgeMultiple(testName:String, Data:Array<AnyObject>, callback:NormalCallback){
|
||||
let finalTestname = generateTestName(testName)
|
||||
weak var expection = self.expectationWithDescription(finalTestname)
|
||||
func didGetResult(result: [AnyObject]) {
|
||||
callback(result, SocketAckEmitter(socket: AbstractSocketTest.socket, ackNum: -1))
|
||||
if let expection = expection {
|
||||
expection.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
AbstractSocketTest.socket.emitWithAck(finalTestname, withItems: Data)(timeoutAfter: 5, callback: didGetResult)
|
||||
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
|
||||
}
|
||||
|
||||
func socketAcknwoledge(testName:String, Data:AnyObject?, callback:NormalCallback){
|
||||
let finalTestname = generateTestName(testName)
|
||||
weak var expection = self.expectationWithDescription(finalTestname)
|
||||
func didGet(result:[AnyObject]) {
|
||||
callback(result, SocketAckEmitter(socket: AbstractSocketTest.socket, ackNum: -1))
|
||||
if let expection = expection {
|
||||
expection.fulfill()
|
||||
}
|
||||
}
|
||||
var ack:OnAckCallback!
|
||||
if let Data = Data {
|
||||
ack = AbstractSocketTest.socket.emitWithAck(finalTestname, Data)
|
||||
} else {
|
||||
ack = AbstractSocketTest.socket.emitWithAck(finalTestname)
|
||||
}
|
||||
ack(timeoutAfter: 20, callback: didGet)
|
||||
|
||||
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//
|
||||
// SocketAcknowledgementTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 27.07.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketAcknowledgementTest: AbstractSocketTest {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
testKind = TestKind.Acknowledgement
|
||||
if AbstractSocketTest.socket == nil {
|
||||
AbstractSocketTest.socket = SocketIOClient(socketURL: "milkbartube.com:6979", opts: [
|
||||
"reconnects": true, // default true
|
||||
"reconnectAttempts": -1, // default -1
|
||||
"reconnectWait": 5, // default 10
|
||||
"forcePolling": false,
|
||||
"forceWebsockets": false,// default false
|
||||
"path": ""])
|
||||
openConnection()
|
||||
}else {
|
||||
AbstractSocketTest.socket.leaveNamespace()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func testConnectionStatus() {
|
||||
super.checkConnectionStatus()
|
||||
}
|
||||
|
||||
func testBasic() {
|
||||
SocketTestCases.testBasic(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testNull() {
|
||||
SocketTestCases.testNull(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testBinary() {
|
||||
SocketTestCases.testBinary(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
SocketTestCases.testArray(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testString() {
|
||||
SocketTestCases.testString(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testBool() {
|
||||
SocketTestCases.testBool(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testInteger() {
|
||||
SocketTestCases.testInteger(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
SocketTestCases.testDouble(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testJSON() {
|
||||
SocketTestCases.testJSON(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testJSONWithBuffer() {
|
||||
SocketTestCases.testJSONWithBuffer(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testUnicode() {
|
||||
SocketTestCases.testUnicode(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testMultipleItems() {
|
||||
SocketTestCases.testMultipleItems(socketAcknwoledgeMultiple)
|
||||
}
|
||||
|
||||
func testMultipleWithBuffer() {
|
||||
SocketTestCases.testMultipleItemsWithBuffer(socketAcknwoledgeMultiple)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
//
|
||||
// ConvertedSocketTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 25.07.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
import Foundation
|
||||
|
||||
class SocketEmitTest: AbstractSocketTest {
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
testKind = TestKind.Emit
|
||||
if AbstractSocketTest.socket == nil {
|
||||
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
|
||||
"reconnects": true, // default true
|
||||
"reconnectAttempts": -1, // default -1
|
||||
"reconnectWait": 5, // default 10
|
||||
"forcePolling": false,
|
||||
"forceWebsockets": false,// default false
|
||||
"path": ""]
|
||||
)
|
||||
openConnection()
|
||||
}else {
|
||||
AbstractSocketTest.socket.leaveNamespace()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testConnectionStatus() {
|
||||
super.checkConnectionStatus()
|
||||
}
|
||||
|
||||
func testBasic() {
|
||||
SocketTestCases.testBasic(socketEmit)
|
||||
}
|
||||
|
||||
func testNull() {
|
||||
SocketTestCases.testNull(socketEmit)
|
||||
}
|
||||
|
||||
func testBinary() {
|
||||
SocketTestCases.testBinary(socketEmit)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
SocketTestCases.testArray(socketEmit)
|
||||
}
|
||||
|
||||
func testString() {
|
||||
SocketTestCases.testString(socketEmit)
|
||||
}
|
||||
|
||||
func testBool() {
|
||||
SocketTestCases.testBool(socketEmit)
|
||||
}
|
||||
|
||||
func testInteger() {
|
||||
SocketTestCases.testInteger(socketEmit)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
SocketTestCases.testDouble(socketEmit)
|
||||
}
|
||||
|
||||
func testJSON() {
|
||||
SocketTestCases.testJSON(socketEmit)
|
||||
}
|
||||
|
||||
func testJSONWithBuffer() {
|
||||
SocketTestCases.testJSONWithBuffer(socketEmit)
|
||||
}
|
||||
|
||||
func testUnicode() {
|
||||
SocketTestCases.testUnicode(socketEmit)
|
||||
}
|
||||
|
||||
func testMultipleItems() {
|
||||
SocketTestCases.testMultipleItems(socketMultipleEmit)
|
||||
}
|
||||
|
||||
func testMultipleWithBuffer() {
|
||||
SocketTestCases.testMultipleItemsWithBuffer(socketMultipleEmit)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//
|
||||
// SocketNamespaceAcknowledgementTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 28.07.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketNamespaceAcknowledgementTest: AbstractSocketTest {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
testKind = TestKind.Acknowledgement
|
||||
if AbstractSocketTest.socket == nil {
|
||||
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
|
||||
"reconnects": true, // default true
|
||||
"reconnectAttempts": -1, // default -1
|
||||
"reconnectWait": 5, // default 10
|
||||
"forcePolling": false,
|
||||
"forceWebsockets": false,// default false
|
||||
"path": "",
|
||||
"nsp": "/swift"])
|
||||
openConnection()
|
||||
}else {
|
||||
AbstractSocketTest.socket.joinNamespace("/swift")
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
func testConnectionStatus() {
|
||||
super.checkConnectionStatus()
|
||||
}
|
||||
|
||||
func testBasic() {
|
||||
SocketTestCases.testBasic(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testNull() {
|
||||
SocketTestCases.testNull(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testBinary() {
|
||||
SocketTestCases.testBinary(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
SocketTestCases.testArray(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testString() {
|
||||
SocketTestCases.testString(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testBool() {
|
||||
SocketTestCases.testBool(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testInteger() {
|
||||
SocketTestCases.testInteger(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
SocketTestCases.testDouble(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testJSON() {
|
||||
SocketTestCases.testJSON(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testJSONWithBuffer() {
|
||||
SocketTestCases.testJSONWithBuffer(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testUnicode() {
|
||||
SocketTestCases.testUnicode(socketAcknwoledge)
|
||||
}
|
||||
|
||||
func testMultipleItems() {
|
||||
SocketTestCases.testMultipleItems(socketAcknwoledgeMultiple)
|
||||
}
|
||||
|
||||
func testMultipleWithBuffer() {
|
||||
SocketTestCases.testMultipleItemsWithBuffer(socketAcknwoledgeMultiple)
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
//
|
||||
// SocketNamespaceEmitTest.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 26.07.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class SocketNamespaceEmitTest: AbstractSocketTest {
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
testKind = TestKind.Emit
|
||||
if AbstractSocketTest.socket == nil {
|
||||
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
|
||||
"reconnects": true, // default true
|
||||
"reconnectAttempts": -1, // default -1
|
||||
"reconnectWait": 5, // default 10
|
||||
"forcePolling": false,
|
||||
"forceWebsockets": false,// default false
|
||||
"path": "",
|
||||
"nsp": "/swift"])
|
||||
openConnection()
|
||||
}else {
|
||||
AbstractSocketTest.socket.joinNamespace("/swift")
|
||||
}
|
||||
}
|
||||
|
||||
func testConnectionStatus() {
|
||||
super.checkConnectionStatus()
|
||||
}
|
||||
|
||||
func testBasic() {
|
||||
SocketTestCases.testBasic(socketEmit)
|
||||
}
|
||||
|
||||
func testNull() {
|
||||
SocketTestCases.testNull(socketEmit)
|
||||
}
|
||||
|
||||
func testBinary() {
|
||||
SocketTestCases.testBinary(socketEmit)
|
||||
}
|
||||
|
||||
func testArray() {
|
||||
SocketTestCases.testArray(socketEmit)
|
||||
}
|
||||
|
||||
func testString() {
|
||||
SocketTestCases.testString(socketEmit)
|
||||
}
|
||||
|
||||
func testBool() {
|
||||
SocketTestCases.testBool(socketEmit)
|
||||
}
|
||||
|
||||
func testInteger() {
|
||||
SocketTestCases.testInteger(socketEmit)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
SocketTestCases.testDouble(socketEmit)
|
||||
}
|
||||
|
||||
func testJSON() {
|
||||
SocketTestCases.testJSON(socketEmit)
|
||||
}
|
||||
|
||||
func testJSONWithBuffer() {
|
||||
SocketTestCases.testJSONWithBuffer(socketEmit)
|
||||
}
|
||||
|
||||
func testUnicode() {
|
||||
SocketTestCases.testUnicode(socketEmit)
|
||||
}
|
||||
|
||||
func testMultipleItems() {
|
||||
SocketTestCases.testMultipleItems(socketMultipleEmit)
|
||||
}
|
||||
|
||||
func testMultipleWithBuffer() {
|
||||
SocketTestCases.testMultipleItemsWithBuffer(socketMultipleEmit)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,6 +13,8 @@ class SocketParserTest: XCTestCase {
|
||||
//Format key: message; namespace-data-binary-id
|
||||
static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [
|
||||
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
|
||||
"25[\"test\"]": ("/", ["test"], [], 5),
|
||||
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
|
||||
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
|
||||
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1),
|
||||
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
|
||||
@@ -43,6 +45,16 @@ class SocketParserTest: XCTestCase {
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testIdEvent() {
|
||||
let message = "25[\"test\"]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testBinaryPlaceholderAsString() {
|
||||
let message = "2[\"test\",\"~~0\"]"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testNameSpaceArrayParse() {
|
||||
let message = "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]"
|
||||
validateParseResult(message)
|
||||
@@ -101,7 +113,7 @@ class SocketParserTest: XCTestCase {
|
||||
let packet = SocketParser.parseString(message)
|
||||
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
|
||||
if case let .Right(packet) = packet {
|
||||
XCTAssertEqual(packet.type, SocketPacket.PacketType(str:type)!)
|
||||
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
|
||||
XCTAssertEqual(packet.nsp, validValues.0)
|
||||
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1))
|
||||
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2))
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
//
|
||||
// SocketTestCases.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 02.08.15.
|
||||
//
|
||||
//
|
||||
|
||||
import XCTest
|
||||
import Foundation
|
||||
|
||||
class SocketTestCases: NSObject {
|
||||
typealias SocketSendFunction = (testName:String, emitData:AnyObject?, callback:NormalCallback)->()
|
||||
|
||||
static func testBasic(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "basicTest"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: nil, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testNull(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testNull"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let _ = result.first as? NSNull {
|
||||
|
||||
}else
|
||||
{
|
||||
XCTFail("Should have NSNull as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: NSNull(), callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testBinary(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testBinary"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let data = result.first as? NSData {
|
||||
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
|
||||
XCTAssertEqual(string, "gakgakgak2")
|
||||
}else {
|
||||
XCTFail("Should have NSData as result")
|
||||
}
|
||||
}
|
||||
let data = NSString(string: "gakgakgak2").dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
abstractSocketSend(testName: testName, emitData: data, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testArray(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testArray"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let array = result.first as? NSArray {
|
||||
XCTAssertEqual(array.count, 2)
|
||||
XCTAssertEqual((array.firstObject! as! String), "test3")
|
||||
XCTAssertEqual((array.lastObject! as! String), "test4")
|
||||
}else {
|
||||
XCTFail("Should have NSArray as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: ["test1", "test2"], callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testString(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testString"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let string = result.first as? String {
|
||||
XCTAssertEqual(string, "polo")
|
||||
}else {
|
||||
XCTFail("Should have String as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: "marco", callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testBool(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testBool"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let bool = result.first as? NSNumber {
|
||||
XCTAssertTrue(bool.boolValue)
|
||||
}else {
|
||||
XCTFail("Should have Boolean as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: false, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testInteger(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testInteger"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let integer = result.first as? Int {
|
||||
XCTAssertEqual(integer, 20)
|
||||
}else {
|
||||
XCTFail("Should have Integer as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: 10, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testDouble(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testDouble"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let double = result.first as? NSNumber {
|
||||
XCTAssertEqual(double.floatValue, 1.2)
|
||||
}else {
|
||||
XCTFail("Should have Double as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: 1.1, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testJSONWithBuffer(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testJSONWithBuffer"
|
||||
let data = "0".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let json = result.first as? NSDictionary {
|
||||
XCTAssertEqual((json.valueForKey("testString")! as! String), "test")
|
||||
XCTAssertEqual((json.valueForKey("testNumber")! as! Int), 15)
|
||||
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).count, 2)
|
||||
XCTAssertEqual(((json.valueForKey("testArray")! as! Array<AnyObject>).last! as! Int), 1)
|
||||
let string = NSString(data: (json.valueForKey("testArray")! as! Array<AnyObject>).first! as! NSData, encoding: NSUTF8StringEncoding)!
|
||||
XCTAssertEqual(string, "gakgakgak2")
|
||||
}else {
|
||||
XCTFail("Should have NSDictionary as result")
|
||||
}
|
||||
}
|
||||
let json = ["name": "test", "testArray": ["hallo"], "nestedTest": ["test": "test"], "number": 15, "buf": data]
|
||||
|
||||
abstractSocketSend(testName: testName, emitData: json, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testJSON(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testJSON"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let json = result.first as? NSDictionary {
|
||||
XCTAssertEqual((json.valueForKey("testString")! as! String), "test")
|
||||
XCTAssertEqual(json.valueForKey("testNumber")! as? Int, 15)
|
||||
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).count, 2)
|
||||
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).first! as? Int, 1)
|
||||
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).last! as? Int, 1)
|
||||
|
||||
}else {
|
||||
XCTFail("Should have NSDictionary as result")
|
||||
}
|
||||
}
|
||||
let json = ["name": "test", "testArray": ["hallo"], "nestedTest": ["test": "test"], "number": 15]
|
||||
|
||||
abstractSocketSend(testName: testName, emitData: json, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testUnicode(abstractSocketSend:SocketSendFunction) {
|
||||
let testName = "testUnicode"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
if let unicode = result.first as? String {
|
||||
XCTAssertEqual(unicode, "🚄")
|
||||
}else {
|
||||
XCTFail("Should have String as result")
|
||||
}
|
||||
}
|
||||
abstractSocketSend(testName: testName, emitData: "🚀", callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testMultipleItemsWithBuffer(abstractSocketMultipleSend:(testName:String, emitData:Array<AnyObject>, callback:NormalCallback)->()) {
|
||||
let testName = "testMultipleItemsWithBuffer"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
XCTAssertEqual(result.count, 5)
|
||||
if result.count != 5 {
|
||||
XCTFail("Fatal Fail. Lost some Data")
|
||||
return
|
||||
}
|
||||
if let array = result.first as? Array<AnyObject> {
|
||||
XCTAssertEqual((array.last! as! Int), 2)
|
||||
XCTAssertEqual((array.first! as! Int), 1)
|
||||
}else {
|
||||
XCTFail("Should have Array as result")
|
||||
}
|
||||
if let dict = result[1] as? NSDictionary {
|
||||
XCTAssertEqual((dict.valueForKey("test") as! String), "bob")
|
||||
|
||||
}else {
|
||||
XCTFail("Should have NSDictionary as result")
|
||||
}
|
||||
if let number = result[2] as? Int {
|
||||
XCTAssertEqual(number, 25)
|
||||
|
||||
}else {
|
||||
XCTFail("Should have Integer as result")
|
||||
}
|
||||
if let string = result[3] as? String {
|
||||
XCTAssertEqual(string, "polo")
|
||||
|
||||
}else {
|
||||
XCTFail("Should have Integer as result")
|
||||
}
|
||||
if let data = result[4] as? NSData {
|
||||
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
|
||||
XCTAssertEqual(string, "gakgakgak2")
|
||||
}else {
|
||||
XCTFail("Should have NSData as result")
|
||||
}
|
||||
}
|
||||
let data = NSString(string: "gakgakgak2").dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let emitArray = [["test1", "test2"], ["test": "test"], 15, "marco", data]
|
||||
abstractSocketMultipleSend(testName: testName, emitData: emitArray, callback: didGetResult)
|
||||
}
|
||||
|
||||
static func testMultipleItems(abstractSocketMultipleSend:(testName:String, emitData:Array<AnyObject>, callback:NormalCallback)->()) {
|
||||
let testName = "testMultipleItems"
|
||||
func didGetResult(result:[AnyObject], ack:SocketAckEmitter?) {
|
||||
XCTAssertEqual(result.count, 5)
|
||||
if result.count != 5 {
|
||||
XCTFail("Fatal Fail. Lost some Data")
|
||||
return
|
||||
}
|
||||
if let array = result.first as? Array<AnyObject> {
|
||||
XCTAssertEqual((array.last! as! Int), 2)
|
||||
XCTAssertEqual((array.first! as! Int), 1)
|
||||
}else {
|
||||
XCTFail("Should have Array as result")
|
||||
}
|
||||
if let dict = result[1] as? NSDictionary {
|
||||
XCTAssertEqual((dict.valueForKey("test") as! String), "bob")
|
||||
|
||||
}else {
|
||||
XCTFail("Should have NSDictionary as result")
|
||||
}
|
||||
if let number = result[2] as? Int {
|
||||
XCTAssertEqual(number, 25)
|
||||
|
||||
}else {
|
||||
XCTFail("Should have Integer as result")
|
||||
}
|
||||
if let string = result[3] as? String {
|
||||
XCTAssertEqual(string, "polo")
|
||||
}else {
|
||||
XCTFail("Should have Integer as result")
|
||||
}
|
||||
if let bool = result[4] as? NSNumber {
|
||||
XCTAssertFalse(bool.boolValue)
|
||||
}else {
|
||||
XCTFail("Should have NSNumber as result")
|
||||
}
|
||||
}
|
||||
let emitArray = [["test1", "test2"], ["test": "test"], 15, "marco", false]
|
||||
abstractSocketMultipleSend(testName: testName, emitData: emitArray, callback: didGetResult)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// TestKind.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Lukas Schmidt on 28.07.15.
|
||||
//
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum TestKind: String {
|
||||
case Emit, Acknowledgement
|
||||
}
|
||||
@@ -34,10 +34,14 @@ public final class SocketAckEmitter: NSObject {
|
||||
}
|
||||
|
||||
public func with(items: AnyObject...) {
|
||||
guard ackNum != -1 else {return}
|
||||
|
||||
socket.emitAck(ackNum, withItems: items)
|
||||
}
|
||||
|
||||
public func with(items: [AnyObject]) {
|
||||
guard ackNum != -1 else {return}
|
||||
|
||||
socket.emitAck(ackNum, withItems: items)
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File diff suppressed because it is too large.
Load diff
@@ -26,9 +26,6 @@
|
||||
import Foundation
|
||||
|
||||
@objc public protocol SocketEngineClient {
|
||||
var socketURL: String {get}
|
||||
var secure: Bool {get}
|
||||
|
||||
func didError(reason: AnyObject)
|
||||
func engineDidClose(reason: String)
|
||||
func parseSocketMessage(msg: String)
|
||||
@@ -1,8 +1,8 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// SocketEnginePacketType.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/16/15.
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -25,14 +25,6 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
func fixDoubleUTF8(inout name: String) {
|
||||
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding)!
|
||||
let latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding)!
|
||||
name = latin1 as String
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(inout str: String) {
|
||||
let latin1 = str.dataUsingEncoding(NSUTF8StringEncoding)!
|
||||
let utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding)!
|
||||
str = utf8 as String
|
||||
}
|
||||
@objc public enum SocketEnginePacketType: Int {
|
||||
case Open, Close, Ping, Pong, Message, Upgrade, Noop
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// SocketEngineSpec.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/7/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc public protocol SocketEngineSpec {
|
||||
weak var client: SocketEngineClient? {get set}
|
||||
var cookies: [NSHTTPCookie]? {get}
|
||||
var sid: String {get}
|
||||
var socketPath: String {get}
|
||||
var urlPolling: String {get}
|
||||
var urlWebSocket: String {get}
|
||||
|
||||
init(client: SocketEngineClient, url: String, options: NSDictionary?)
|
||||
|
||||
func close()
|
||||
func open(opts: [String: AnyObject]?)
|
||||
func send(msg: String, withData datas: [NSData])
|
||||
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
|
||||
}
|
||||
@@ -24,23 +24,12 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private func emitAckCallback(socket: SocketIOClient, num: Int?) -> SocketAckEmitter? {
|
||||
return num != nil ? SocketAckEmitter(socket: socket, ackNum: num!) : nil
|
||||
}
|
||||
|
||||
struct SocketEventHandler {
|
||||
let event: String
|
||||
let callback: NormalCallback
|
||||
let id: NSUUID
|
||||
let callback: NormalCallback
|
||||
|
||||
init(event: String, id: NSUUID = NSUUID(), callback: NormalCallback) {
|
||||
self.event = event
|
||||
self.id = id
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
func executeCallback(items: [AnyObject], withAck ack: Int? = nil, withAckType type: Int? = nil,
|
||||
withSocket socket: SocketIOClient) {
|
||||
self.callback(items, emitAckCallback(socket, num: ack))
|
||||
func executeCallback(items: [AnyObject], withAck ack: Int, withSocket socket: SocketIOClient) {
|
||||
callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// SocketFixUTF8.swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 3/16/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
func fixDoubleUTF8(string: String) -> String {
|
||||
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
|
||||
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
|
||||
return latin1 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
func doubleEncodeUTF8(string: String) -> String {
|
||||
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
|
||||
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
|
||||
return utf8 as String
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
}
|
||||
@@ -25,99 +25,98 @@
|
||||
import Foundation
|
||||
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue: dispatch_queue_t!
|
||||
|
||||
public let socketURL: String
|
||||
|
||||
public private(set) var engine: SocketEngine?
|
||||
public private(set) var secure = false
|
||||
|
||||
public private(set) var engine: SocketEngineSpec?
|
||||
public private(set) var status = SocketIOClientStatus.NotConnected
|
||||
|
||||
public var forceNew = false
|
||||
public var nsp = "/"
|
||||
public var opts: [String: AnyObject]?
|
||||
public var options: Set<SocketIOClientOption>
|
||||
public var reconnects = true
|
||||
public var reconnectWait = 10
|
||||
public var sid: String? {
|
||||
return engine?.sid
|
||||
}
|
||||
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let logType = "SocketIOClient"
|
||||
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
private var anyHandler: ((SocketAnyEvent) -> Void)?
|
||||
private var currentReconnectAttempt = 0
|
||||
private var handlers = ContiguousArray<SocketEventHandler>()
|
||||
private var handlers = [SocketEventHandler]()
|
||||
private var connectParams: [String: AnyObject]?
|
||||
private var reconnectTimer: NSTimer?
|
||||
|
||||
private let reconnectAttempts: Int!
|
||||
private var ackHandlers = SocketAckManager()
|
||||
private var currentAck = -1
|
||||
|
||||
|
||||
private(set) var currentAck = -1
|
||||
private(set) var handleQueue = dispatch_get_main_queue()
|
||||
private(set) var reconnectAttempts = -1
|
||||
|
||||
var waitingData = [SocketPacket]()
|
||||
|
||||
/**
|
||||
Create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(var socketURL: String, opts: [String: AnyObject]? = nil) {
|
||||
Type safe way to create a new SocketIOClient. opts can be omitted
|
||||
*/
|
||||
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
|
||||
self.options = options
|
||||
|
||||
if socketURL["https://"].matches().count != 0 {
|
||||
self.secure = true
|
||||
self.options.insertIgnore(.Secure(true))
|
||||
}
|
||||
|
||||
socketURL = socketURL["http://"] ~= ""
|
||||
socketURL = socketURL["https://"] ~= ""
|
||||
self.socketURL = socketURL["https?://"] ~= ""
|
||||
|
||||
self.socketURL = socketURL
|
||||
self.opts = opts
|
||||
|
||||
if let connectParams = opts?["connectParams"] as? [String: AnyObject] {
|
||||
self.connectParams = connectParams
|
||||
for option in options ?? [] {
|
||||
switch option {
|
||||
case .ConnectParams(let params):
|
||||
connectParams = params
|
||||
case .Reconnects(let reconnects):
|
||||
self.reconnects = reconnects
|
||||
case .ReconnectAttempts(let attempts):
|
||||
reconnectAttempts = attempts
|
||||
case .ReconnectWait(let wait):
|
||||
reconnectWait = abs(wait)
|
||||
case .Nsp(let nsp):
|
||||
self.nsp = nsp
|
||||
case .Log(let log):
|
||||
DefaultSocketLogger.Logger.log = log
|
||||
case .Logger(let logger):
|
||||
DefaultSocketLogger.Logger = logger
|
||||
case .HandleQueue(let queue):
|
||||
handleQueue = queue
|
||||
case .ForceNew(let force):
|
||||
forceNew = force
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if let logger = opts?["logger"] as? SocketLogger {
|
||||
Logger = logger
|
||||
}
|
||||
|
||||
if let log = opts?["log"] as? Bool {
|
||||
Logger.log = log
|
||||
}
|
||||
|
||||
if let nsp = opts?["nsp"] as? String {
|
||||
self.nsp = nsp
|
||||
}
|
||||
|
||||
if let reconnects = opts?["reconnects"] as? Bool {
|
||||
self.reconnects = reconnects
|
||||
}
|
||||
|
||||
if let reconnectAttempts = opts?["reconnectAttempts"] as? Int {
|
||||
self.reconnectAttempts = reconnectAttempts
|
||||
} else {
|
||||
self.reconnectAttempts = -1
|
||||
}
|
||||
|
||||
if let reconnectWait = opts?["reconnectWait"] as? Int {
|
||||
self.reconnectWait = abs(reconnectWait)
|
||||
}
|
||||
|
||||
if let handleQueue = opts?["handleQueue"] as? dispatch_queue_t {
|
||||
self.handleQueue = handleQueue
|
||||
} else {
|
||||
self.handleQueue = dispatch_get_main_queue()
|
||||
}
|
||||
self.options.insertIgnore(.Path("/socket.io"))
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
|
||||
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
|
||||
*/
|
||||
public convenience init(socketURL: String, options: NSDictionary?) {
|
||||
self.init(socketURL: socketURL,
|
||||
options: Set<SocketIOClientOption>.NSDictionaryToSocketOptionsSet(options ?? [:]))
|
||||
}
|
||||
|
||||
deinit {
|
||||
Logger.log("Client is being deinit", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
|
||||
engine?.close()
|
||||
}
|
||||
|
||||
private func addEngine() -> SocketEngine {
|
||||
Logger.log("Adding engine", type: logType)
|
||||
|
||||
let newEngine = SocketEngine(client: self, opts: opts)
|
||||
|
||||
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
|
||||
|
||||
let newEngine = SocketEngine(client: self, url: socketURL, options: options ?? [])
|
||||
|
||||
engine = newEngine
|
||||
return newEngine
|
||||
}
|
||||
@@ -128,53 +127,53 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
/**
|
||||
Closes the socket. Only reopen the same socket if you know what you're doing.
|
||||
Will turn off automatic reconnects.
|
||||
Pass true to fast if you're closing from a background task
|
||||
*/
|
||||
Closes the socket. Only reopen the same socket if you know what you're doing.
|
||||
Will turn off automatic reconnects.
|
||||
Pass true to fast if you're closing from a background task
|
||||
*/
|
||||
public func close() {
|
||||
Logger.log("Closing socket", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
|
||||
|
||||
reconnects = false
|
||||
didDisconnect("Closed")
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server.
|
||||
*/
|
||||
Connect to the server.
|
||||
*/
|
||||
public func connect() {
|
||||
connect(timeoutAfter: 0, withTimeoutHandler: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
public func connect(timeoutAfter timeoutAfter: Int,
|
||||
withTimeoutHandler handler: (() -> Void)?) {
|
||||
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
|
||||
|
||||
|
||||
guard status != .Connected else {
|
||||
return
|
||||
}
|
||||
|
||||
if status == .Closed {
|
||||
Logger.log("Warning! This socket was previously closed. This might be dangerous!",
|
||||
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
|
||||
type: logType)
|
||||
}
|
||||
|
||||
status = SocketIOClientStatus.Connecting
|
||||
addEngine().open(connectParams)
|
||||
|
||||
guard timeoutAfter != 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
status = .Connecting
|
||||
|
||||
if engine == nil || forceNew {
|
||||
addEngine().open(connectParams)
|
||||
} else {
|
||||
engine?.open(connectParams)
|
||||
}
|
||||
|
||||
guard timeoutAfter != 0 else { return }
|
||||
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {
|
||||
if self.status != .Connected {
|
||||
self.status = .Closed
|
||||
self.engine?.close(fast: true)
|
||||
|
||||
dispatch_after(time, handleQueue) {[weak self] in
|
||||
if let this = self where this.status != .Connected {
|
||||
this.status = .Closed
|
||||
this.engine?.close()
|
||||
|
||||
handler?()
|
||||
}
|
||||
@@ -202,7 +201,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
|
||||
func didConnect() {
|
||||
Logger.log("Socket connected", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
|
||||
status = .Connected
|
||||
currentReconnectAttempt = 0
|
||||
clearReconnectTimer()
|
||||
@@ -217,81 +216,79 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
return
|
||||
}
|
||||
|
||||
Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
|
||||
|
||||
status = .Closed
|
||||
reconnects = false
|
||||
|
||||
// Make sure the engine is actually dead.
|
||||
engine?.close(fast: true)
|
||||
engine?.close()
|
||||
handleEvent("disconnect", data: [reason], isInternalMessage: true)
|
||||
}
|
||||
|
||||
/// error
|
||||
public func didError(reason: AnyObject) {
|
||||
Logger.error("%@", type: logType, args: reason)
|
||||
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
|
||||
|
||||
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
|
||||
isInternalMessage: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as close
|
||||
*/
|
||||
Same as close
|
||||
*/
|
||||
public func disconnect() {
|
||||
close()
|
||||
}
|
||||
|
||||
/**
|
||||
Send a message to the server
|
||||
*/
|
||||
Send a message to the server
|
||||
*/
|
||||
public func emit(event: String, _ items: AnyObject...) {
|
||||
emit(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
Same as emit, but meant for Objective-C
|
||||
*/
|
||||
public func emit(event: String, withItems items: [AnyObject]) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
dispatch_async(emitQueue) {
|
||||
self._emit([event] + items)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
|
||||
an ack.
|
||||
*/
|
||||
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
|
||||
return emitWithAck(event, withItems: items)
|
||||
}
|
||||
|
||||
/**
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
Same as emitWithAck, but for Objective-C
|
||||
*/
|
||||
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
|
||||
return createOnAck([event] + items)
|
||||
}
|
||||
|
||||
private func _emit(data: [AnyObject], ack: Int? = nil) {
|
||||
guard status == .Connected else {
|
||||
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
|
||||
return
|
||||
}
|
||||
|
||||
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
|
||||
let str = packet.packetString
|
||||
|
||||
Logger.log("Emitting: %@", type: logType, args: str)
|
||||
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
|
||||
|
||||
if packet.type == .BinaryEvent {
|
||||
engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
engine?.send(str, withData: nil)
|
||||
}
|
||||
engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
|
||||
// If the server wants to know that the client received data
|
||||
@@ -301,14 +298,9 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
|
||||
let str = packet.packetString
|
||||
|
||||
Logger.log("Emitting Ack: %@", type: self.logType, args: str)
|
||||
|
||||
if packet.type == SocketPacket.PacketType.BinaryAck {
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
} else {
|
||||
self.engine?.send(str, withData: nil)
|
||||
}
|
||||
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
|
||||
|
||||
self.engine?.send(str, withData: packet.binary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -327,152 +319,159 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
// Called when the socket gets an ack for something it sent
|
||||
func handleAck(ack: Int, data: AnyObject?) {
|
||||
Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
guard status == .Connected else {return}
|
||||
|
||||
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
|
||||
|
||||
ackHandlers.executeAck(ack,
|
||||
items: (data as? [AnyObject]) ?? (data != nil ? [data!] : []))
|
||||
}
|
||||
|
||||
/**
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
Causes an event to be handled. Only use if you know what you're doing.
|
||||
*/
|
||||
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool,
|
||||
wantsAck ack: Int? = nil) {
|
||||
withAck ack: Int = -1) {
|
||||
guard status == .Connected || isInternalMessage else {
|
||||
return
|
||||
}
|
||||
|
||||
Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
|
||||
|
||||
if anyHandler != nil {
|
||||
dispatch_async(handleQueue) {
|
||||
self.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
dispatch_async(handleQueue) {
|
||||
self.anyHandler?(SocketAnyEvent(event: event, items: data))
|
||||
|
||||
for handler in self.handlers where handler.event == event {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
}
|
||||
|
||||
for handler in handlers where handler.event == event {
|
||||
if let ack = ack {
|
||||
dispatch_async(handleQueue) {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
} else {
|
||||
dispatch_async(handleQueue) {
|
||||
handler.executeCallback(data, withAck: ack, withSocket: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Leaves nsp and goes back to /
|
||||
*/
|
||||
Leaves nsp and goes back to /
|
||||
*/
|
||||
public func leaveNamespace() {
|
||||
if nsp != "/" {
|
||||
engine?.send("1\(nsp)", withData: nil)
|
||||
engine?.send("1\(nsp)", withData: [])
|
||||
nsp = "/"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins nsp if it is not /
|
||||
*/
|
||||
Joins nsp if it is not /
|
||||
*/
|
||||
public func joinNamespace() {
|
||||
Logger.log("Joining namespace", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
|
||||
|
||||
if nsp != "/" {
|
||||
engine?.send("0\(nsp)", withData: nil)
|
||||
engine?.send("0\(nsp)", withData: [])
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Joins namespace /
|
||||
*/
|
||||
Joins namespace /
|
||||
*/
|
||||
public func joinNamespace(namespace: String) {
|
||||
self.nsp = namespace
|
||||
joinNamespace()
|
||||
}
|
||||
|
||||
/**
|
||||
Removes handler(s)
|
||||
*/
|
||||
Removes handler(s)
|
||||
*/
|
||||
public func off(event: String) {
|
||||
Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
|
||||
|
||||
handlers = ContiguousArray(handlers.filter { $0.event != event })
|
||||
handlers = handlers.filter { $0.event != event }
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
Removes a handler with the specified UUID gotten from an `on` or `once`
|
||||
*/
|
||||
public func on(event: String, callback: NormalCallback) {
|
||||
Logger.log("Adding handler for event: %@", type: logType, args: event)
|
||||
public func off(id id: NSUUID) {
|
||||
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
|
||||
|
||||
let handler = SocketEventHandler(event: event, callback: callback)
|
||||
handlers = handlers.filter { $0.id != id }
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
public func on(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
|
||||
|
||||
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
|
||||
handlers.append(handler)
|
||||
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a single-use handler for an event.
|
||||
*/
|
||||
public func once(event: String, callback: NormalCallback) {
|
||||
Logger.log("Adding once handler for event: %@", type: logType, args: event)
|
||||
Adds a single-use handler for an event.
|
||||
Returns: A unique id for the handler
|
||||
*/
|
||||
public func once(event: String, callback: NormalCallback) -> NSUUID {
|
||||
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
|
||||
|
||||
let id = NSUUID()
|
||||
|
||||
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
|
||||
guard let this = self else {return}
|
||||
this.handlers = ContiguousArray(this.handlers.filter {$0.id != id})
|
||||
this.off(id: id)
|
||||
callback(data, ack)
|
||||
}
|
||||
|
||||
|
||||
handlers.append(handler)
|
||||
|
||||
return handler.id
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all handlers.
|
||||
Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
*/
|
||||
public func removeAllHandlers() {
|
||||
handlers.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
Adds a handler that will be called on every event.
|
||||
*/
|
||||
public func onAny(handler: (SocketAnyEvent) -> Void) {
|
||||
anyHandler = handler
|
||||
}
|
||||
|
||||
/**
|
||||
Same as connect
|
||||
*/
|
||||
Same as connect
|
||||
*/
|
||||
public func open() {
|
||||
connect()
|
||||
}
|
||||
|
||||
public func parseSocketMessage(msg: String) {
|
||||
dispatch_async(handleQueue) {
|
||||
dispatch_async(parseQueue) {
|
||||
SocketParser.parseSocketMessage(msg, socket: self)
|
||||
}
|
||||
}
|
||||
|
||||
public func parseBinaryData(data: NSData) {
|
||||
dispatch_async(handleQueue) {
|
||||
dispatch_async(parseQueue) {
|
||||
SocketParser.parseBinaryData(data, socket: self)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tries to reconnect to the server.
|
||||
*/
|
||||
Tries to reconnect to the server.
|
||||
*/
|
||||
public func reconnect() {
|
||||
engine?.stopPolling()
|
||||
tryReconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all handlers.
|
||||
Can be used after disconnecting to break any potential remaining retain cycles.
|
||||
*/
|
||||
public func removeAllHandlers() {
|
||||
handlers.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
private func tryReconnect() {
|
||||
if reconnectTimer == nil {
|
||||
Logger.log("Starting reconnect", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
|
||||
|
||||
status = .Reconnecting
|
||||
|
||||
@@ -482,7 +481,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@objc private func _tryReconnect() {
|
||||
if status == .Connected {
|
||||
clearReconnectTimer()
|
||||
@@ -490,7 +489,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
|
||||
clearReconnectTimer()
|
||||
didDisconnect("Reconnect Failed")
|
||||
@@ -498,7 +496,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
return
|
||||
}
|
||||
|
||||
Logger.log("Trying to reconnect", type: logType)
|
||||
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
|
||||
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
|
||||
isInternalMessage: true)
|
||||
|
||||
@@ -506,3 +504,22 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
connect()
|
||||
}
|
||||
}
|
||||
|
||||
// Test extensions
|
||||
extension SocketIOClient {
|
||||
var testHandlers: [SocketEventHandler] {
|
||||
return handlers
|
||||
}
|
||||
|
||||
func setTestable() {
|
||||
status = .Connected
|
||||
}
|
||||
|
||||
func setTestEngine(engine: SocketEngineSpec?) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
func emitTest(event: String, _ data: AnyObject...) {
|
||||
self._emit([event] + data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//
|
||||
// SocketIOClientOption .swift
|
||||
// Socket.IO-Client-Swift
|
||||
//
|
||||
// Created by Erik Little on 10/17/15.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol ClientOption: CustomStringConvertible, Hashable {
|
||||
func getSocketIOOptionValue() -> AnyObject?
|
||||
}
|
||||
|
||||
public enum SocketIOClientOption: ClientOption {
|
||||
case ConnectParams([String: AnyObject])
|
||||
case Cookies([NSHTTPCookie])
|
||||
case ExtraHeaders([String: String])
|
||||
case ForceNew(Bool)
|
||||
case ForcePolling(Bool)
|
||||
case ForceWebsockets(Bool)
|
||||
case HandleQueue(dispatch_queue_t)
|
||||
case Log(Bool)
|
||||
case Logger(SocketLogger)
|
||||
case Nsp(String)
|
||||
case Path(String)
|
||||
case Reconnects(Bool)
|
||||
case ReconnectAttempts(Int)
|
||||
case ReconnectWait(Int)
|
||||
case Secure(Bool)
|
||||
case SelfSigned(Bool)
|
||||
case SessionDelegate(NSURLSessionDelegate)
|
||||
case VoipEnabled(Bool)
|
||||
|
||||
public var description: String {
|
||||
if let label = Mirror(reflecting: self).children.first?.label {
|
||||
return String(label[label.startIndex]).lowercaseString + String(label.characters.dropFirst())
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return description.hashValue
|
||||
}
|
||||
|
||||
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
|
||||
switch (key, value) {
|
||||
case ("connectParams", let params as [String: AnyObject]):
|
||||
return .ConnectParams(params)
|
||||
case ("reconnects", let reconnects as Bool):
|
||||
return .Reconnects(reconnects)
|
||||
case ("reconnectAttempts", let attempts as Int):
|
||||
return .ReconnectAttempts(attempts)
|
||||
case ("reconnectWait", let wait as Int):
|
||||
return .ReconnectWait(wait)
|
||||
case ("forceNew", let force as Bool):
|
||||
return .ForceNew(force)
|
||||
case ("forcePolling", let force as Bool):
|
||||
return .ForcePolling(force)
|
||||
case ("forceWebsockets", let force as Bool):
|
||||
return .ForceWebsockets(force)
|
||||
case ("nsp", let nsp as String):
|
||||
return .Nsp(nsp)
|
||||
case ("cookies", let cookies as [NSHTTPCookie]):
|
||||
return .Cookies(cookies)
|
||||
case ("log", let log as Bool):
|
||||
return .Log(log)
|
||||
case ("logger", let logger as SocketLogger):
|
||||
return .Logger(logger)
|
||||
case ("sessionDelegate", let delegate as NSURLSessionDelegate):
|
||||
return .SessionDelegate(delegate)
|
||||
case ("path", let path as String):
|
||||
return .Path(path)
|
||||
case ("extraHeaders", let headers as [String: String]):
|
||||
return .ExtraHeaders(headers)
|
||||
case ("handleQueue", let queue as dispatch_queue_t):
|
||||
return .HandleQueue(queue)
|
||||
case ("voipEnabled", let enable as Bool):
|
||||
return .VoipEnabled(enable)
|
||||
case ("secure", let secure as Bool):
|
||||
return .Secure(secure)
|
||||
case ("selfSigned", let selfSigned as Bool):
|
||||
return .SelfSigned(selfSigned)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func getSocketIOOptionValue() -> AnyObject? {
|
||||
return Mirror(reflecting: self).children.first?.value as? AnyObject
|
||||
}
|
||||
}
|
||||
|
||||
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
extension Set where Element: ClientOption {
|
||||
mutating func insertIgnore(element: Element) {
|
||||
if !contains(element) {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
|
||||
static func NSDictionaryToSocketOptionsSet(dict: NSDictionary) -> Set<SocketIOClientOption> {
|
||||
var options = Set<SocketIOClientOption>()
|
||||
|
||||
for (rawKey, value) in dict {
|
||||
if let key = rawKey as? String, opt = SocketIOClientOption.keyValueToSocketIOClientOption(key, value: value) {
|
||||
options.insertIgnore(opt)
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
func SocketOptionsSetToNSDictionary() -> NSDictionary {
|
||||
let options = NSMutableDictionary()
|
||||
|
||||
for option in self {
|
||||
options[option.description] = option.getSocketIOOptionValue()
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@
|
||||
import Foundation
|
||||
|
||||
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
|
||||
case NotConnected, Closed, Connecting, Connected, Reconnecting
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case NotConnected:
|
||||
@@ -39,6 +41,4 @@ import Foundation
|
||||
return "Reconnecting"
|
||||
}
|
||||
}
|
||||
|
||||
case NotConnected, Closed, Connecting, Connected, Reconnecting
|
||||
}
|
||||
@@ -24,9 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
public protocol SocketLogger {
|
||||
public protocol SocketLogger: class {
|
||||
/// Whether to log or not
|
||||
var log: Bool {get set}
|
||||
|
||||
@@ -56,6 +54,8 @@ public extension SocketLogger {
|
||||
}
|
||||
}
|
||||
|
||||
struct DefaultSocketLogger: SocketLogger {
|
||||
class DefaultSocketLogger: SocketLogger {
|
||||
static var Logger: SocketLogger = DefaultSocketLogger()
|
||||
|
||||
var log = false
|
||||
}
|
||||
@@ -21,14 +21,15 @@
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct SocketPacket {
|
||||
private let placeholders: Int
|
||||
private var currentPlace = 0
|
||||
|
||||
private static let logType = "SocketPacket"
|
||||
|
||||
private static let logType = "SocketPacket"
|
||||
|
||||
let nsp: String
|
||||
let id: Int
|
||||
@@ -36,14 +37,6 @@ struct SocketPacket {
|
||||
|
||||
enum PacketType: Int {
|
||||
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
|
||||
|
||||
init?(str: String) {
|
||||
if let int = Int(str), raw = PacketType(rawValue: int) {
|
||||
self = raw
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var args: [AnyObject]? {
|
||||
@@ -52,7 +45,7 @@ struct SocketPacket {
|
||||
if data.count == 0 {
|
||||
return nil
|
||||
} else {
|
||||
if type == PacketType.Event || type == PacketType.BinaryEvent {
|
||||
if type == .Event || type == .BinaryEvent {
|
||||
arr.removeAtIndex(0)
|
||||
return arr
|
||||
} else {
|
||||
@@ -102,7 +95,9 @@ struct SocketPacket {
|
||||
}
|
||||
}
|
||||
|
||||
private func completeMessage(var message: String, ack: Bool) -> String {
|
||||
private func completeMessage(message: String, ack: Bool) -> String {
|
||||
var restOfMessage = ""
|
||||
|
||||
if data.count == 0 {
|
||||
return message + "]"
|
||||
}
|
||||
@@ -114,27 +109,25 @@ struct SocketPacket {
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
let jsonString = NSString(data: jsonSend, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String + ","
|
||||
restOfMessage += jsonString! as String + ","
|
||||
} catch {
|
||||
Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType)
|
||||
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
|
||||
type: SocketPacket.logType)
|
||||
}
|
||||
} else if var str = arg as? String {
|
||||
str = str["\n"] ~= "\\\\n"
|
||||
str = str["\r"] ~= "\\\\r"
|
||||
|
||||
message += "\"\(str)\","
|
||||
} else if let str = arg as? String {
|
||||
restOfMessage += "\"" + ((str["\n"] ~= "\\\\n")["\r"] ~= "\\\\r") + "\","
|
||||
} else if arg is NSNull {
|
||||
message += "null,"
|
||||
restOfMessage += "null,"
|
||||
} else {
|
||||
message += "\(arg),"
|
||||
restOfMessage += "\(arg),"
|
||||
}
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
message.removeAtIndex(message.endIndex.predecessor())
|
||||
if restOfMessage != "" {
|
||||
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
|
||||
}
|
||||
|
||||
return message + "]"
|
||||
return message + restOfMessage + "]"
|
||||
}
|
||||
|
||||
private func createAck() -> String {
|
||||
@@ -150,7 +143,7 @@ struct SocketPacket {
|
||||
if nsp == "/" {
|
||||
msg = "6\(binary.count)-\(id)["
|
||||
} else {
|
||||
msg = "6\(binary.count)-/\(nsp),\(id)["
|
||||
msg = "6\(binary.count)-\(nsp),\(id)["
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,7 +190,7 @@ struct SocketPacket {
|
||||
private func createPacketString() -> String {
|
||||
let str: String
|
||||
|
||||
if type == PacketType.Event || type == PacketType.BinaryEvent {
|
||||
if type == .Event || type == .BinaryEvent {
|
||||
str = createMessageForEvent()
|
||||
} else {
|
||||
str = createAck()
|
||||
@@ -209,6 +202,7 @@ struct SocketPacket {
|
||||
mutating func fillInPlaceholders() {
|
||||
for i in 0..<data.count {
|
||||
if let str = data[i] as? String, num = str["~~(\\d)"].groups() {
|
||||
// Fill in binary placeholder with data
|
||||
data[i] = binary[Int(num[1])!]
|
||||
} else if data[i] is NSDictionary || data[i] is NSArray {
|
||||
data[i] = _fillInPlaceholders(data[i])
|
||||
@@ -231,14 +225,8 @@ struct SocketPacket {
|
||||
}
|
||||
|
||||
return newDict
|
||||
} else if let arr = data as? NSArray {
|
||||
let newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = _fillInPlaceholders(arr[i])
|
||||
}
|
||||
|
||||
return newArr
|
||||
} else if let arr = data as? [AnyObject] {
|
||||
return arr.map({_fillInPlaceholders($0)})
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
@@ -273,17 +261,13 @@ extension SocketPacket {
|
||||
private extension SocketPacket {
|
||||
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
|
||||
if let bin = data as? NSData {
|
||||
let placeholder = ["_placeholder" :true, "num": binary.count]
|
||||
let placeholder = ["_placeholder": true, "num": binary.count]
|
||||
|
||||
binary.append(bin)
|
||||
|
||||
return placeholder
|
||||
} else if var arr = data as? [AnyObject] {
|
||||
for i in 0..<arr.count {
|
||||
arr[i] = shred(arr[i], binary: &binary)
|
||||
}
|
||||
|
||||
return arr
|
||||
} else if let arr = data as? [AnyObject] {
|
||||
return arr.map({shred($0, binary: &binary)})
|
||||
} else if let dict = data as? NSDictionary {
|
||||
let mutDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
@@ -297,18 +281,9 @@ private extension SocketPacket {
|
||||
}
|
||||
}
|
||||
|
||||
static func deconstructData(var data: [AnyObject]) -> ([AnyObject], [NSData]) {
|
||||
static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
|
||||
var binary = [NSData]()
|
||||
|
||||
for i in 0..<data.count {
|
||||
if data[i] is NSArray || data[i] is NSDictionary {
|
||||
data[i] = shred(data[i], binary: &binary)
|
||||
} else if let bin = data[i] as? NSData {
|
||||
data[i] = ["_placeholder" :true, "num": binary.count]
|
||||
binary.append(bin)
|
||||
}
|
||||
}
|
||||
|
||||
return (data, binary)
|
||||
return (data.map({shred($0, binary: &binary)}), binary)
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ class SocketParser {
|
||||
switch pack.type {
|
||||
case .Event where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.handleEvent(pack.event, data: pack.args ?? [],
|
||||
isInternalMessage: false, wantsAck: pack.id)
|
||||
isInternalMessage: false, withAck: pack.id)
|
||||
case .Ack where isCorrectNamespace(pack.nsp, socket):
|
||||
socket.handleAck(pack.id, data: pack.data)
|
||||
case .BinaryEvent where isCorrectNamespace(pack.nsp, socket):
|
||||
@@ -56,14 +56,15 @@ class SocketParser {
|
||||
case .Error:
|
||||
socket.didError(pack.data)
|
||||
default:
|
||||
Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
|
||||
static func parseString(message: String) -> Either<String, SocketPacket> {
|
||||
var parser = SocketStringReader(message: message)
|
||||
|
||||
guard let type = SocketPacket.PacketType(str: parser.read(1)) else {
|
||||
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
|
||||
return .Left("Invalid packet type")
|
||||
}
|
||||
|
||||
@@ -143,20 +144,20 @@ class SocketParser {
|
||||
static func parseSocketMessage(message: String, socket: SocketIOClient) {
|
||||
guard !message.isEmpty else { return }
|
||||
|
||||
Logger.log("Parsing %@", type: "SocketParser", args: message)
|
||||
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
|
||||
|
||||
switch parseString(message) {
|
||||
case .Left(let err):
|
||||
Logger.error("\(err): %@", type: "SocketParser", args: message)
|
||||
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
|
||||
case .Right(let pack):
|
||||
Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
|
||||
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
|
||||
handlePacket(pack, withSocket: socket)
|
||||
}
|
||||
}
|
||||
|
||||
static func parseBinaryData(data: NSData, socket: SocketIOClient) {
|
||||
guard !socket.waitingData.isEmpty else {
|
||||
Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -170,7 +171,7 @@ class SocketParser {
|
||||
|
||||
if packet.type != .BinaryAck {
|
||||
socket.handleEvent(packet.event, data: packet.args ?? [],
|
||||
isInternalMessage: false, wantsAck: packet.id)
|
||||
isInternalMessage: false, withAck: packet.id)
|
||||
} else {
|
||||
socket.handleAck(packet.id, data: packet.args)
|
||||
}
|
||||
File renamed without changes.
@@ -25,10 +25,10 @@
|
||||
import Foundation
|
||||
|
||||
public typealias AckCallback = ([AnyObject]) -> Void
|
||||
public typealias NormalCallback = ([AnyObject], SocketAckEmitter?) -> Void
|
||||
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
|
||||
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
|
||||
|
||||
enum Either<E, V> {
|
||||
case Left(E)
|
||||
case Right(V)
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -3,6 +3,19 @@
|
||||
// Websocket.swift
|
||||
//
|
||||
// Created by Dalton Cherry on 7/16/14.
|
||||
// Copyright (c) 2014-2015 Dalton Cherry.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -34,7 +47,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//B-F reserved.
|
||||
}
|
||||
|
||||
enum CloseCode : UInt16 {
|
||||
public enum CloseCode : UInt16 {
|
||||
case Normal = 1000
|
||||
case GoingAway = 1001
|
||||
case ProtocolError = 1002
|
||||
@@ -47,6 +60,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
case MessageTooBig = 1009
|
||||
}
|
||||
|
||||
public static let ErrorDomain = "WebSocket"
|
||||
|
||||
enum InternalErrorCode : UInt16 {
|
||||
// 0-999 WebSocket status codes not used
|
||||
case OutputStreamWriteError = 1
|
||||
@@ -55,7 +70,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//Where the callback is executed. It defaults to the main UI thread queue.
|
||||
public var queue = dispatch_get_main_queue()
|
||||
|
||||
var optionalProtocols : Array<String>?
|
||||
var optionalProtocols : [String]?
|
||||
//Constant Values.
|
||||
let headerWSUpgradeName = "Upgrade"
|
||||
let headerWSUpgradeValue = "websocket"
|
||||
@@ -91,7 +106,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
public var onText: ((String) -> Void)?
|
||||
public var onData: ((NSData) -> Void)?
|
||||
public var onPong: ((Void) -> Void)?
|
||||
public var headers = Dictionary<String,String>()
|
||||
public var headers = [String: String]()
|
||||
public var voipEnabled = false
|
||||
public var selfSignedSSL = false
|
||||
private var security: SSLSecurity?
|
||||
@@ -106,41 +121,56 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
private var connected = false
|
||||
private var isCreated = false
|
||||
private var writeQueue = NSOperationQueue()
|
||||
private var readStack = Array<WSResponse>()
|
||||
private var inputQueue = Array<NSData>()
|
||||
private var readStack = [WSResponse]()
|
||||
private var inputQueue = [NSData]()
|
||||
private var fragBuffer: NSData?
|
||||
private var certValidated = false
|
||||
private var didDisconnect = false
|
||||
|
||||
//init the websocket with a url
|
||||
public init(url: NSURL) {
|
||||
//used for setting protocols.
|
||||
public init(url: NSURL, protocols: [String]? = nil) {
|
||||
self.url = url
|
||||
writeQueue.maxConcurrentOperationCount = 1
|
||||
}
|
||||
//used for setting protocols.
|
||||
public convenience init(url: NSURL, protocols: Array<String>) {
|
||||
self.init(url: url)
|
||||
optionalProtocols = protocols
|
||||
}
|
||||
|
||||
///Connect to the websocket server on a background thread
|
||||
public func connect() {
|
||||
if isCreated {
|
||||
return
|
||||
}
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard !isCreated else { return }
|
||||
|
||||
dispatch_async(queue) { [weak self] in
|
||||
self?.didDisconnect = false
|
||||
})
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { [weak self] in
|
||||
}
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) { [weak self] in
|
||||
self?.isCreated = true
|
||||
self?.createHTTPRequest()
|
||||
self?.isCreated = false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
///disconnect from the websocket server
|
||||
public func disconnect() {
|
||||
writeError(CloseCode.Normal.rawValue)
|
||||
/**
|
||||
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
|
||||
|
||||
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
|
||||
|
||||
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
|
||||
|
||||
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
|
||||
*/
|
||||
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
|
||||
switch forceTimeout {
|
||||
case .Some(let seconds) where seconds > 0:
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [unowned self] in
|
||||
self.disconnectStream(nil)
|
||||
}
|
||||
fallthrough
|
||||
case .None:
|
||||
writeError(CloseCode.Normal.rawValue)
|
||||
|
||||
default:
|
||||
self.disconnectStream(nil)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
///write a string to the websocket. This sends it as a text frame.
|
||||
@@ -168,7 +198,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
var port = url.port
|
||||
if port == nil {
|
||||
if url.scheme == "wss" || url.scheme == "https" {
|
||||
if ["wss", "https"].contains(url.scheme) {
|
||||
port = 443
|
||||
} else {
|
||||
port = 80
|
||||
@@ -192,18 +222,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||
private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) {
|
||||
let nsKey: NSString = key
|
||||
let nsVal: NSString = val
|
||||
CFHTTPMessageSetHeaderFieldValue(urlRequest,
|
||||
nsKey,
|
||||
nsVal)
|
||||
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
|
||||
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
|
||||
}
|
||||
//generate a websocket key as needed in rfc
|
||||
private func generateWebSocketKey() -> String {
|
||||
var key = ""
|
||||
let seed = 16
|
||||
for (var i = 0; i < seed; i++) {
|
||||
for _ in 0..<seed {
|
||||
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
|
||||
key += "\(Character(uni))"
|
||||
}
|
||||
@@ -225,7 +251,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
guard let inStream = inputStream, let outStream = outputStream else { return }
|
||||
inStream.delegate = self
|
||||
outStream.delegate = self
|
||||
if url.scheme == "wss" || url.scheme == "https" {
|
||||
if ["wss", "https"].contains(url.scheme) {
|
||||
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
} else {
|
||||
@@ -236,7 +262,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
}
|
||||
if selfSignedSSL {
|
||||
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
}
|
||||
@@ -245,12 +271,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
|
||||
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
|
||||
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
|
||||
if (resIn != errSecSuccess) {
|
||||
if resIn != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
if (resOut != errSecSuccess) {
|
||||
if resOut != errSecSuccess {
|
||||
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
|
||||
disconnectStream(error)
|
||||
return
|
||||
@@ -271,7 +297,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//delegate for the stream methods. Processes incoming bytes
|
||||
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||
|
||||
if let sec = security where !certValidated && (eventCode == .HasBytesAvailable || eventCode == .HasSpaceAvailable) {
|
||||
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
|
||||
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
|
||||
if let trust: AnyObject = possibleTrust {
|
||||
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
|
||||
@@ -285,7 +311,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
if eventCode == .HasBytesAvailable {
|
||||
if(aStream == inputStream) {
|
||||
if aStream == inputStream {
|
||||
processInputStream()
|
||||
}
|
||||
} else if eventCode == .ErrorOccurred {
|
||||
@@ -317,50 +343,51 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
if length > 0 {
|
||||
|
||||
guard length > 0 else { return }
|
||||
|
||||
if !connected {
|
||||
connected = processHTTP(buffer, bufferLen: length)
|
||||
if !connected {
|
||||
connected = processHTTP(buffer, bufferLen: length)
|
||||
if !connected {
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, length)
|
||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
} else {
|
||||
var process = false
|
||||
if inputQueue.count == 0 {
|
||||
process = true
|
||||
}
|
||||
inputQueue.append(NSData(bytes: buffer, length: length))
|
||||
if process {
|
||||
dequeueInput()
|
||||
}
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, length)
|
||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
} else {
|
||||
var process = false
|
||||
if inputQueue.count == 0 {
|
||||
process = true
|
||||
}
|
||||
inputQueue.append(NSData(bytes: buffer, length: length))
|
||||
if process {
|
||||
dequeueInput()
|
||||
}
|
||||
}
|
||||
}
|
||||
///dequeue the incoming input so it is processed in order
|
||||
private func dequeueInput() {
|
||||
if inputQueue.count > 0 {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if fragBuffer != nil {
|
||||
let combine = NSMutableData(data: fragBuffer!)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
fragBuffer = nil
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
processRawMessage(buffer, bufferLen: work.length)
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
dequeueInput()
|
||||
guard !inputQueue.isEmpty else { return }
|
||||
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if let fragBuffer = fragBuffer {
|
||||
let combine = NSMutableData(data: fragBuffer)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
self.fragBuffer = nil
|
||||
}
|
||||
let buffer = UnsafePointer<UInt8>(work.bytes)
|
||||
processRawMessage(buffer, bufferLen: work.length)
|
||||
inputQueue = inputQueue.filter{$0 != data}
|
||||
dequeueInput()
|
||||
}
|
||||
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
||||
var k = 0
|
||||
var totalSize = 0
|
||||
for var i = 0; i < bufferLen; i++ {
|
||||
for i in 0..<bufferLen {
|
||||
if buffer[i] == CRLFBytes[k] {
|
||||
k++
|
||||
if k == 3 {
|
||||
@@ -373,13 +400,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if totalSize > 0 {
|
||||
if validateResponse(buffer, bufferLen: totalSize) {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let connectBlock = s.onConnect {
|
||||
connectBlock()
|
||||
}
|
||||
s.onConnect?()
|
||||
s.delegate?.websocketDidConnect(s)
|
||||
})
|
||||
}
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
@@ -400,14 +425,42 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
||||
let headers = cfHeaders.takeRetainedValue() as NSDictionary
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
if let acceptKey = headers[headerWSAcceptName] as? NSString {
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
///read a 16 bit big endian value from a buffer
|
||||
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
|
||||
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
|
||||
}
|
||||
|
||||
///read a 64 bit big endian value from a buffer
|
||||
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
|
||||
var value = UInt64(0)
|
||||
for i in 0...7 {
|
||||
value = (value << 8) | UInt64(buffer[offset + i])
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
///write a 16 bit big endian value to a buffer
|
||||
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
|
||||
buffer[offset + 0] = UInt8(value >> 8)
|
||||
buffer[offset + 1] = UInt8(value & 0xff)
|
||||
}
|
||||
|
||||
///write a 64 bit big endian value to a buffer
|
||||
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
|
||||
for i in 0...7 {
|
||||
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
|
||||
}
|
||||
}
|
||||
|
||||
///process the websocket data
|
||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
let response = readStack.last
|
||||
@@ -415,17 +468,16 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
}
|
||||
if response != nil && response!.bytesLeft > 0 {
|
||||
let resp = response!
|
||||
var len = resp.bytesLeft
|
||||
var extra = bufferLen - resp.bytesLeft
|
||||
if resp.bytesLeft > bufferLen {
|
||||
if let response = response where response.bytesLeft > 0 {
|
||||
var len = response.bytesLeft
|
||||
var extra = bufferLen - response.bytesLeft
|
||||
if response.bytesLeft > bufferLen {
|
||||
len = bufferLen
|
||||
extra = 0
|
||||
}
|
||||
resp.bytesLeft -= len
|
||||
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
processResponse(resp)
|
||||
response.bytesLeft -= len
|
||||
response.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
processResponse(response)
|
||||
let offset = bufferLen - extra
|
||||
if extra > 0 {
|
||||
processExtra((buffer+offset), bufferLen: extra)
|
||||
@@ -433,19 +485,19 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
return
|
||||
} else {
|
||||
let isFin = (FinMask & buffer[0])
|
||||
let receivedOpcode = (OpCodeMask & buffer[0])
|
||||
let receivedOpcode = OpCode(rawValue: (OpCodeMask & buffer[0]))
|
||||
let isMasked = (MaskMask & buffer[1])
|
||||
let payloadLen = (PayloadLenMask & buffer[1])
|
||||
var offset = 2
|
||||
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
if (isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != .Pong {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
|
||||
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
|
||||
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
|
||||
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
|
||||
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
@@ -457,13 +509,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
if receivedOpcode == OpCode.ConnectionClose.rawValue {
|
||||
if receivedOpcode == .ConnectionClose {
|
||||
var code = CloseCode.Normal.rawValue
|
||||
if payloadLen == 1 {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
} else if payloadLen > 1 {
|
||||
let codeBuffer = UnsafePointer<UInt16>((buffer+offset))
|
||||
code = codeBuffer[0].bigEndian
|
||||
code = WebSocket.readUint16(buffer, offset: offset)
|
||||
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
@@ -489,12 +540,10 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
var dataLength = UInt64(payloadLen)
|
||||
if dataLength == 127 {
|
||||
let bytes = UnsafePointer<UInt64>((buffer+offset))
|
||||
dataLength = bytes[0].bigEndian
|
||||
dataLength = WebSocket.readUint64(buffer, offset: offset)
|
||||
offset += sizeof(UInt64)
|
||||
} else if dataLength == 126 {
|
||||
let bytes = UnsafePointer<UInt16>((buffer+offset))
|
||||
dataLength = UInt64(bytes[0].bigEndian)
|
||||
dataLength = UInt64(WebSocket.readUint16(buffer, offset: offset))
|
||||
offset += sizeof(UInt16)
|
||||
}
|
||||
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
|
||||
@@ -512,14 +561,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
} else {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
}
|
||||
if receivedOpcode == OpCode.Pong.rawValue {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
if receivedOpcode == .Pong {
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let pongBlock = s.onPong {
|
||||
pongBlock()
|
||||
}
|
||||
s.onPong?()
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
})
|
||||
}
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
@@ -532,15 +579,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if isControlFrame {
|
||||
response = nil //don't append pings
|
||||
}
|
||||
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
|
||||
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
var isNew = false
|
||||
if(response == nil) {
|
||||
if receivedOpcode == OpCode.ContinueFrame.rawValue {
|
||||
if response == nil {
|
||||
if receivedOpcode == .ContinueFrame {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
doDisconnect(errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode))
|
||||
@@ -549,11 +596,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
isNew = true
|
||||
response = WSResponse()
|
||||
response!.code = OpCode(rawValue: receivedOpcode)!
|
||||
response!.code = receivedOpcode!
|
||||
response!.bytesLeft = Int(dataLength)
|
||||
response!.buffer = NSMutableData(data: data)
|
||||
} else {
|
||||
if receivedOpcode == OpCode.ContinueFrame.rawValue {
|
||||
if receivedOpcode == .ContinueFrame {
|
||||
response!.bytesLeft = Int(dataLength)
|
||||
} else {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
@@ -564,19 +611,19 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
response!.buffer!.appendData(data)
|
||||
}
|
||||
if response != nil {
|
||||
response!.bytesLeft -= Int(len)
|
||||
response!.frameCount++
|
||||
response!.isFin = isFin > 0 ? true : false
|
||||
if(isNew) {
|
||||
readStack.append(response!)
|
||||
if let response = response {
|
||||
response.bytesLeft -= Int(len)
|
||||
response.frameCount++
|
||||
response.isFin = isFin > 0 ? true : false
|
||||
if isNew {
|
||||
readStack.append(response)
|
||||
}
|
||||
processResponse(response!)
|
||||
processResponse(response)
|
||||
}
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
if(extra > 0) {
|
||||
if extra > 0 {
|
||||
processExtra((buffer+step), bufferLen: extra)
|
||||
}
|
||||
}
|
||||
@@ -605,22 +652,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
return false
|
||||
}
|
||||
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let textBlock = s.onText {
|
||||
textBlock(str! as String)
|
||||
}
|
||||
s.onText?(str! as String)
|
||||
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
||||
})
|
||||
}
|
||||
} else if response.code == .BinaryFrame {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let dataBlock = s.onData {
|
||||
dataBlock(data)
|
||||
}
|
||||
s.onData?(data)
|
||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||
})
|
||||
}
|
||||
}
|
||||
readStack.removeLast()
|
||||
return true
|
||||
@@ -630,23 +673,22 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
///Create an error
|
||||
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
|
||||
var details = Dictionary<String,String>()
|
||||
var details = [String: String]()
|
||||
details[NSLocalizedDescriptionKey] = detail
|
||||
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
|
||||
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
|
||||
}
|
||||
|
||||
///write a an error to the socket
|
||||
private func writeError(code: UInt16) {
|
||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||
let buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||
buffer[0] = code.bigEndian
|
||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
WebSocket.writeUint16(buffer, offset: 0, value: code)
|
||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||
}
|
||||
///used to write things to the stream
|
||||
private func dequeueWrite(data: NSData, code: OpCode) {
|
||||
if !isConnected {
|
||||
return
|
||||
}
|
||||
guard isConnected else { return }
|
||||
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
//stream isn't ready, let's wait
|
||||
guard let s = self else { return }
|
||||
@@ -660,13 +702,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
buffer[1] = CUnsignedChar(dataLength)
|
||||
} else if dataLength <= Int(UInt16.max) {
|
||||
buffer[1] = 126
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||
sizeBuffer[0] = UInt16(dataLength).bigEndian
|
||||
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
|
||||
offset += sizeof(UInt16)
|
||||
} else {
|
||||
buffer[1] = 127
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||
sizeBuffer[0] = UInt64(dataLength).bigEndian
|
||||
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
|
||||
offset += sizeof(UInt64)
|
||||
}
|
||||
buffer[1] |= s.MaskMask
|
||||
@@ -674,7 +714,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||
offset += sizeof(UInt32)
|
||||
|
||||
for (var i = 0; i < dataLength; i++) {
|
||||
for i in 0..<dataLength {
|
||||
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
|
||||
offset += 1
|
||||
}
|
||||
@@ -709,15 +749,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
///used to preform the disconnect delegate
|
||||
private func doDisconnect(error: NSError?) {
|
||||
if !didDisconnect {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.didDisconnect = true
|
||||
if let disconnect = s.onDisconnect {
|
||||
disconnect(error)
|
||||
}
|
||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||
})
|
||||
guard !didDisconnect else { return }
|
||||
|
||||
dispatch_async(queue) { [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.didDisconnect = true
|
||||
s.onDisconnect?(error)
|
||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -728,23 +766,23 @@ private class SSLCert {
|
||||
var key: SecKeyRef?
|
||||
|
||||
/**
|
||||
Designated init for certificates
|
||||
|
||||
- parameter data: is the binary data of the certificate
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
Designated init for certificates
|
||||
|
||||
- parameter data: is the binary data of the certificate
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(data: NSData) {
|
||||
self.certData = data
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init for public keys
|
||||
|
||||
- parameter key: is the public key to be used
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
Designated init for public keys
|
||||
|
||||
- parameter key: is the public key to be used
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
@@ -767,60 +805,63 @@ private class SSLSecurity {
|
||||
*/
|
||||
convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
var collect = Array<SSLCert>()
|
||||
for path in paths {
|
||||
if let d = NSData(contentsOfFile: path as String) {
|
||||
collect.append(SSLCert(data: d))
|
||||
|
||||
let certs = paths.reduce([SSLCert]()) { (var certs: [SSLCert], path: String) -> [SSLCert] in
|
||||
if let data = NSData(contentsOfFile: path) {
|
||||
certs.append(SSLCert(data: data))
|
||||
}
|
||||
return certs
|
||||
}
|
||||
self.init(certs:collect, usePublicKeys: usePublicKeys)
|
||||
|
||||
self.init(certs: certs, usePublicKeys: usePublicKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
Designated init
|
||||
|
||||
- parameter keys: is the certificates or public keys to use
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
Designated init
|
||||
|
||||
- parameter keys: is the certificates or public keys to use
|
||||
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
|
||||
var collect = Array<SecKeyRef>()
|
||||
for cert in certs {
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
|
||||
let pubKeys = certs.reduce([SecKeyRef]()) { (var pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
|
||||
if let data = cert.certData where cert.key == nil {
|
||||
cert.key = self.extractPublicKey(data)
|
||||
}
|
||||
if let k = cert.key {
|
||||
collect.append(k)
|
||||
if let key = cert.key {
|
||||
pubKeys.append(key)
|
||||
}
|
||||
return pubKeys
|
||||
}
|
||||
self.pubKeys = collect
|
||||
|
||||
self.pubKeys = pubKeys
|
||||
self.isReady = true
|
||||
})
|
||||
} else {
|
||||
var collect = Array<NSData>()
|
||||
for cert in certs {
|
||||
if let d = cert.certData {
|
||||
collect.append(d)
|
||||
}
|
||||
}
|
||||
self.certificates = collect
|
||||
} else {
|
||||
let certificates = certs.reduce([NSData]()) { (var certificates: [NSData], cert: SSLCert) -> [NSData] in
|
||||
if let data = cert.certData {
|
||||
certificates.append(data)
|
||||
}
|
||||
return certificates
|
||||
}
|
||||
self.certificates = certificates
|
||||
self.isReady = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Valid the trust and domain name.
|
||||
|
||||
- parameter trust: is the serverTrust to validate
|
||||
- parameter domain: is the CN domain to validate
|
||||
|
||||
- returns: if the key was successfully validated
|
||||
*/
|
||||
Valid the trust and domain name.
|
||||
|
||||
- parameter trust: is the serverTrust to validate
|
||||
- parameter domain: is the CN domain to validate
|
||||
|
||||
- returns: if the key was successfully validated
|
||||
*/
|
||||
func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
|
||||
var tries = 0
|
||||
@@ -840,23 +881,18 @@ private class SSLSecurity {
|
||||
SecTrustSetPolicies(trust,policy)
|
||||
if self.usePublicKeys {
|
||||
if let keys = self.pubKeys {
|
||||
var trustedCount = 0
|
||||
let serverPubKeys = publicKeyChainForTrust(trust)
|
||||
for serverKey in serverPubKeys as [AnyObject] {
|
||||
for key in keys as [AnyObject] {
|
||||
if serverKey.isEqual(key) {
|
||||
trustedCount++
|
||||
break
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
if trustedCount == serverPubKeys.count {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if let certs = self.certificates {
|
||||
let serverCerts = certificateChainForTrust(trust)
|
||||
var collect = Array<SecCertificate>()
|
||||
var collect = [SecCertificate]()
|
||||
for cert in certs {
|
||||
collect.append(SecCertificateCreateWithData(nil,cert)!)
|
||||
}
|
||||
@@ -883,71 +919,72 @@ private class SSLSecurity {
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate data
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
Get the public key from a certificate data
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKey(data: NSData) -> SecKeyRef? {
|
||||
let possibleCert = SecCertificateCreateWithData(nil,data)
|
||||
if let cert = possibleCert {
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
return nil
|
||||
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
|
||||
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key from a certificate
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
Get the public key from a certificate
|
||||
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
|
||||
var possibleTrust: SecTrust?
|
||||
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
|
||||
if let trust = possibleTrust {
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
return nil
|
||||
|
||||
guard let trust = possibleTrust else { return nil }
|
||||
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
/**
|
||||
Get the certificate chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain for
|
||||
|
||||
- returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
|
||||
var collect = Array<NSData>()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
collect.append(SecCertificateCopyData(cert!))
|
||||
Get the certificate chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain for
|
||||
|
||||
- returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
|
||||
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (var certificates: [NSData], index: Int) -> [NSData] in
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
certificates.append(SecCertificateCopyData(cert!))
|
||||
return certificates
|
||||
}
|
||||
return collect
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Get the public key chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
|
||||
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
|
||||
var collect = Array<SecKeyRef>()
|
||||
Get the public key chain for the trust
|
||||
|
||||
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
|
||||
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
|
||||
let cert = SecTrustGetCertificateAtIndex(trust,i)
|
||||
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (var keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
|
||||
let cert = SecTrustGetCertificateAtIndex(trust, index)
|
||||
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
|
||||
collect.append(key)
|
||||
keys.append(key)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
return collect
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user