Compare commits

...
26 Commits
Author SHA1 Message Date
Erik 1b4b571be6 bump version 2016-04-11 18:58:02 -04:00
Erik Little c9f653ef2c Merge pull request #344 from socketio/development
Development
2016-04-11 18:55:27 -04:00
Erik 3073130598 change to how server gives id 2016-04-11 18:51:22 -04:00
Erik ed3d49001f bump websocket version 2016-04-10 13:59:21 -04:00
Erik 4ee196c5fb add default value to namespace in socketparsable 2016-04-04 11:28:20 -04:00
Erik baca9fc8da small refactors 2016-03-31 21:31:24 -04:00
Erik 1a5ac74984 Merge branch 'master' into development
* master:
  set targetted device family to 3
  use 7.3 image
2016-03-25 17:02:52 -04:00
Erik Little 6c779e84d2 Merge pull request #335 from craigkj312/master
actual fix for carthage
2016-03-25 17:01:53 -04:00
Kyle Craig 293d71bf97 set targetted device family to 3 2016-03-25 15:54:57 -05:00
Erik 2f1f77141e add test for objc api 2016-03-25 10:00:14 -04:00
Erik d4c01183ab style 2016-03-25 09:48:04 -04:00
Erik 5d81377e0a use 7.3 image 2016-03-24 14:46:32 -04:00
Erik 8f8d5acdba use 7.3 image 2016-03-24 14:17:49 -04:00
Erik a0167ae213 remove deprecated methods 2016-03-23 13:39:22 -04:00
Erik 4f5837afa7 don't need objc on this method anymore 2016-03-22 10:15:09 -04:00
Erik 718caba9d9 remove nstimer 2016-03-22 09:56:56 -04:00
Erik Little 2919d4a5ce Merge pull request #330 from socketio/development
Development
2016-03-22 09:06:13 -04:00
Erik a53b7167b6 update version and readme 2016-03-22 09:05:57 -04:00
Erik 6c6b4f32c9 Update for swift 2.2 2016-03-22 09:00:27 -04:00
Erik 3a842469ec fix log placement 2016-03-16 13:13:22 -04:00
Erik 596a499041 work on fixing reconnect() 2016-03-11 13:41:09 -05:00
Erik 76a572e735 refactor reconnect 2016-03-11 13:03:40 -05:00
Erik 6da9463c8d whitespace 2016-03-03 10:11:08 -05:00
Erik 2f7a5405b0 add check for fast upgrade 2016-03-03 09:59:33 -05:00
Erik 62131ef904 make sure we don't handle poll messages if we aren't polling 2016-03-03 09:57:39 -05:00
Erik 5976ef1752 bump websocket version 2016-02-27 19:43:21 -05:00
22 changed files with 270 additions and 271 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode7
osx_image: xcode7.3
before_install:
- cd Socket.IO-Test-Server/
- npm install
+6 -4
View File
@@ -55,7 +55,9 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@
- Can be used from Objective-C
##Installation
Requires Swift 2/Xcode 7
Requires Swift 2.2/Xcode 7.3
If you need Swift 2.1/Xcode 7.2 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
@@ -86,7 +88,7 @@ Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 5.5.0 # Or latest version
github "socketio/socket.io-client-swift" ~> 6.1.0 # Or latest version
```
Run `carthage update --platform ios,macosx`.
@@ -100,7 +102,7 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 5.5.0' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 6.1.0' # Or latest version
```
Install pods:
@@ -128,7 +130,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.5.0", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v6.1.0", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
+2 -2
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIOClientSwift"
s.version = "5.5.0"
s.version = "6.1.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.5.0' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v6.1.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -116,6 +116,7 @@
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */; };
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */; };
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */; };
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketClientSpec.swift */; };
@@ -187,6 +188,7 @@
74171E621C10CD240062D398 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = "<group>"; };
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketEngineTest.swift; sourceTree = "<group>"; };
7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePollable.swift; path = Source/SocketEnginePollable.swift; sourceTree = "<group>"; };
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SocketObjectiveCTest.m; sourceTree = "<group>"; };
74321DC91C2D939A00CF6F43 /* SocketAckManagerTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketAckManagerTest.swift; sourceTree = "<group>"; };
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketParserTest.swift; sourceTree = "<group>"; };
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
@@ -326,6 +328,7 @@
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */,
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */,
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */,
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */,
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */,
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */,
572EF2471B51F18A00EEBB58 /* Supporting Files */,
@@ -513,7 +516,7 @@
572EF20E1B51F12F00EEBB58 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0710;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0720;
TargetAttributes = {
572EF2181B51F16C00EEBB58 = {
@@ -687,6 +690,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */,
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */,
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */,
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
@@ -1169,6 +1173,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
@@ -1269,7 +1274,7 @@
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@@ -1320,7 +1325,7 @@
PRODUCT_NAME = SocketIO;
SDKROOT = appletvos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.0;
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
+45
View File
@@ -0,0 +1,45 @@
//
// SocketObjectiveCTest.m
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/25/16.
//
// Merely tests whether the Objective-C api breaks
//
#import <XCTest/XCTest.h>
@import SocketIOClientSwift;
@interface SocketObjectiveCTest : XCTestCase
@property SocketIOClient* socket;
@end
@implementation SocketObjectiveCTest
- (void)setUp {
[super setUp];
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
self.socket = [[SocketIOClient alloc] initWithSocketURL:url options:nil];
}
- (void)testOnSyntax {
[self.socket on:@"someCallback" callback:^(NSArray* data, SocketAckEmitter* ack) {
[ack with:@[@1]];
}];
}
- (void)testEmitSyntax {
[self.socket emit:@"testEmit" withItems:@[@YES]];
}
- (void)testEmitWithAckSyntax {
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]];
}
- (void)testOffSyntax {
[self.socket off:@"test"];
}
@end
+7 -1
View File
@@ -25,6 +25,7 @@ class SocketParserTest: XCTestCase {
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"4{\"test\":2}": ("/", [["test": 2]], [], -1),
"41": ("/", [1], [], -1)]
func testDisconnect() {
@@ -87,6 +88,11 @@ class SocketParserTest: XCTestCase {
validateParseResult(message)
}
func testErrorTypeDictionary() {
let message = "4{\"test\":2}"
validateParseResult(message)
}
func testErrorTypeInt() {
let message = "41"
validateParseResult(message)
@@ -113,7 +119,7 @@ class SocketParserTest: XCTestCase {
func validateParseResult(message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = testSocket.parseString(message)
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
let type = message.substringWithRange(Range<String.Index>(message.startIndex..<message.startIndex.advancedBy(1)))
if case let .Right(packet) = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
XCTAssertEqual(packet.nsp, validValues.0)
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketAckEmitter: NSObject {
public final class SocketAckEmitter : NSObject {
let socket: SocketIOClient
let ackNum: Int
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
private struct SocketAck: Hashable, Equatable {
private struct SocketAck : Hashable, Equatable {
let ack: Int
var callback: AckCallback!
var hashValue: Int {
+1 -1
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketAnyEvent: NSObject {
public final class SocketAnyEvent : NSObject {
public let event: String
public let items: NSArray?
override public var description: String {
+1 -1
View File
@@ -22,7 +22,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
protocol SocketClientSpec: class {
protocol SocketClientSpec : class {
var nsp: String { get set }
var waitingPackets: [SocketPacket] { get set }
+21 -43
View File
@@ -24,7 +24,7 @@
import Foundation
public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket {
public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
@@ -47,7 +47,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public private(set) var forcePolling = false
public private(set) var forceWebsockets = false
public private(set) var invalidated = false
public private(set) var pingTimer: NSTimer?
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: NSURLSession?
@@ -123,18 +122,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(client: SocketEngineClient, urlString: String, options: Set<SocketIOClientOption>) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options)
}
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
@@ -184,16 +171,12 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
return false
}
}
public func close(reason: String) {
disconnect(reason)
}
/// Starts the connection to the server
public func connect() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
close("reconnect")
disconnect("reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
@@ -285,7 +268,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public func didError(error: String) {
DefaultSocketLogger.Logger.error(error, type: logType)
client?.engineDidError(error)
close(error)
disconnect(error)
}
public func disconnect(reason: String) {
@@ -295,7 +278,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
@@ -303,6 +285,10 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return postSendClose(nil, nil, nil)
}
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
@@ -397,8 +383,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
createWebsocketAndConnect()
}
startPingTimer()
sendPing()
if !forceWebsockets {
doPoll()
@@ -420,11 +405,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
upgradeTransport()
}
}
public func open() {
connect()
}
public func parseEngineData(data: NSData) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
@@ -483,30 +464,28 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
websocket = false
}
@objc private func sendPing() {
private func sendPing() {
if !connected {
return
}
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
pongsMissed += 1
write("", withType: .Ping, withData: [])
}
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
pongsMissed += 1
write("", withType: .Ping, withData: [])
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(pingInterval * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
self?.sendPing()
}
}
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
@@ -558,7 +537,6 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
+1 -1
View File
@@ -25,6 +25,6 @@
import Foundation
@objc public enum SocketEnginePacketType: Int {
@objc public enum SocketEnginePacketType : Int {
case Open, Close, Ping, Pong, Message, Upgrade, Noop
}
+11 -11
View File
@@ -25,7 +25,7 @@
import Foundation
/// Protocol that is used to implement socket.io polling support
public protocol SocketEnginePollable: SocketEngineSpec {
public protocol SocketEnginePollable : SocketEngineSpec {
var invalidated: Bool { get }
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
@@ -100,19 +100,19 @@ extension SocketEnginePollable {
}
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
if !polling || closed || invalidated {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
if !polling || closed || invalidated || fastUpgrade {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
}
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self else { return }
guard let this = self where this.polling else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
@@ -123,7 +123,7 @@ extension SocketEnginePollable {
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
-3
View File
@@ -37,7 +37,6 @@ import Foundation
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: dispatch_queue_t! { get }
var pingTimer: NSTimer? { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: dispatch_queue_t! { get }
@@ -50,13 +49,11 @@ import Foundation
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
@available(*, deprecated=5.5, message="Please use disconnect") func close(reason: String)
func connect()
func didError(error: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
@available(*, deprecated=5.5, message="Please use connect") func open()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
+1 -1
View File
@@ -26,7 +26,7 @@
import Foundation
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
var ws: WebSocket? { get }
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
+73 -132
View File
@@ -24,11 +24,21 @@
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
public let socketURL: NSURL
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public private(set) var status = SocketIOClientStatus.NotConnected {
didSet {
switch status {
case .Connected:
reconnecting = false
currentReconnectAttempt = 0
default:
break
}
}
}
public var forceNew = false
public var nsp = "/"
@@ -36,7 +46,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
return nsp + "#" + (engine?.sid ?? "")
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
@@ -46,8 +56,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private var reconnecting = false
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
@@ -55,9 +65,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
var waitingPackets = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
/// Type safe way to create a new SocketIOClient. opts can be omitted
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
self.options = options
self.socketURL = socketURL
@@ -94,26 +102,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
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(socketURL: NSURL, options: Set<SocketIOClientOption>)`
*/
/// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
/// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
public convenience init(socketURL: NSURL, options: NSDictionary?) {
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
}
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(socketURLString: String, options: Set<SocketIOClientOption> = []) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options)
}
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(socketURLString: String, options: NSDictionary?) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.disconnect("Client Deinit")
@@ -127,26 +121,12 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return engine!
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
@available(*, deprecated=5.3, message="Please use disconnect()")
public func close() {
disconnect()
}
/**
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)")
@@ -184,10 +164,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
this._emit(items, ack: ack)
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
@@ -203,8 +180,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
@@ -224,10 +199,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/**
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
Will turn off automatic reconnects.
*/
/// Disconnects the socket. Only reconnect the same socket if you know what you're doing.
/// Will turn off automatic reconnects.
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
@@ -235,54 +208,46 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
didDisconnect("Disconnect")
}
/**
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) {[emitData = [event] + items] in
self._emit(emitData)
}
_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
dispatch_async(emitQueue) {
guard self.status == .Connected else {
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: self.nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
@@ -301,10 +266,15 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
public func engineDidClose(reason: String) {
waitingPackets.removeAll()
if status != .Closed {
status = .NotConnected
}
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
} else if !reconnecting {
reconnecting = true
tryReconnectWithReason(reason)
}
}
@@ -318,16 +288,14 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else {return}
guard status == .Connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack, items: 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, withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
@@ -344,9 +312,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Leaves nsp and goes back to /
*/
/// Leaves nsp and goes back to /
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
@@ -354,9 +320,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Joins namespace
*/
/// Joins namespace
public func joinNamespace(namespace: String) {
nsp = namespace
@@ -366,28 +330,22 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Removes handler(s)
*/
/// Removes handler(s) based on name
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
/// Removes a handler with the specified UUID gotten from an `on` or `once`
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
/// 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)
@@ -397,10 +355,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
/// 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)
@@ -417,18 +373,11 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
return handler.id
}
/**
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
}
@available(*, deprecated=5.3, message="Please use one of the connect methods)")
public func open() {
connect()
}
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
@@ -443,47 +392,35 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
}
/**
Tries to reconnect to the server.
*/
/// Tries to reconnect to the server.
public func reconnect() {
tryReconnectWithReason("manual reconnect")
guard !reconnecting else { return }
engine?.disconnect("manual reconnect")
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
/// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles.
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnectWithReason(reason: String) {
if reconnectTimer == nil {
if reconnecting {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
handleEvent("reconnect", data: [reason], isInternalMessage: true)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
_tryReconnect()
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
private func _tryReconnect() {
if !reconnecting {
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
return didDisconnect("Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
@@ -492,6 +429,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
currentReconnectAttempt += 1
connect()
let dispatchAfter = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(reconnectWait) * NSEC_PER_SEC))
dispatch_after(dispatchAfter, dispatch_get_main_queue(), _tryReconnect)
}
}
+3 -3
View File
@@ -24,11 +24,11 @@
import Foundation
protocol ClientOption: CustomStringConvertible, Hashable {
protocol ClientOption : CustomStringConvertible, Hashable {
func getSocketIOOptionValue() -> AnyObject
}
public enum SocketIOClientOption: ClientOption {
public enum SocketIOClientOption : ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
@@ -152,7 +152,7 @@ public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
return lhs.description == rhs.description
}
extension Set where Element: ClientOption {
extension Set where Element : ClientOption {
mutating func insertIgnore(element: Element) {
if !contains(element) {
insert(element)
+2 -4
View File
@@ -24,8 +24,8 @@
import Foundation
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
case NotConnected, Closed, Connecting, Connected, Reconnecting
@objc public enum SocketIOClientStatus : Int, CustomStringConvertible {
case NotConnected, Closed, Connecting, Connected
public var description: String {
switch self {
@@ -37,8 +37,6 @@ import Foundation
return "Connecting"
case Connected:
return "Connected"
case Reconnecting:
return "Reconnecting"
}
}
}
+2 -2
View File
@@ -24,7 +24,7 @@
import Foundation
public protocol SocketLogger: class {
public protocol SocketLogger : class {
/// Whether to log or not
var log: Bool {get set}
@@ -54,7 +54,7 @@ public extension SocketLogger {
}
}
class DefaultSocketLogger: SocketLogger {
class DefaultSocketLogger : SocketLogger {
static var Logger: SocketLogger = DefaultSocketLogger()
var log = false
+8 -7
View File
@@ -22,7 +22,7 @@
import Foundation
protocol SocketParsable: SocketClientSpec {
protocol SocketParsable : SocketClientSpec {
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
}
@@ -76,7 +76,7 @@ extension SocketParsable {
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace: String?
var namespace = "/"
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
@@ -116,26 +116,27 @@ extension SocketParsable {
switch parseData(noPlaceholders) {
case let .Left(err):
// If first you don't succeed, try again
// Errors aren't always enclosed in an array
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
nsp: namespace, placeholders: placeholders))
} else {
return .Left(err)
}
case let .Right(data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
+1 -1
View File
@@ -18,7 +18,7 @@ infix operator <~ { associativity none precedence 130 }
private let lock = dispatch_semaphore_create(1)
private var swiftRegexCache = [String: NSRegularExpression]()
internal final class SwiftRegex: NSObject, BooleanType {
internal final class SwiftRegex : NSObject, BooleanType {
var target: String
var regex: NSRegularExpression
+74 -48
View File
@@ -109,7 +109,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
public var headers = [String: String]()
public var voipEnabled = false
public var selfSignedSSL = false
private var security: SSLSecurity?
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var isConnected :Bool {
@@ -167,8 +167,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
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)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .None:
@@ -180,30 +180,42 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func writeString(str: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func writeData(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .BinaryFrame)
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
public func writePing(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .Ping)
dequeueWrite(data, code: .Ping, writeCompletion: completion)
}
//private method that starts the connection
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
@@ -283,18 +295,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
@@ -309,13 +321,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
let bytes = UnsafePointer<UInt8>(data.bytes)
var timeout = 5000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
guard let this = self else { return }
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
timeout -= 100
if timeout < 0 {
this.cleanupStream()
this.doDisconnect(this.errorWithDetail("write wait timed out", code: 2))
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
@@ -352,7 +363,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
writeQueue.waitUntilAllOperationsAreFinished()
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
@@ -425,7 +440,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break //do nothing, we are going to collect more data
break //do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
@@ -544,10 +559,10 @@ public class WebSocket : NSObject, NSStreamDelegate {
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)
return
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
@@ -600,7 +615,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
let data: NSData
if len < 0 {
len = 0
data = NSData()
@@ -736,7 +751,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode) {
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
@@ -785,6 +800,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
total += len
}
if total >= offset {
if let queue = self?.queue, callback = writeCompletion {
dispatch_async(queue) {
callback()
}
}
break
}
}
@@ -814,7 +835,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
private class SSLCert {
public class SSLCert {
var certData: NSData?
var key: SecKeyRef?
@@ -825,7 +846,7 @@ private class SSLCert {
- returns: a representation security object to be used with
*/
init(data: NSData) {
public init(data: NSData) {
self.certData = data
}
@@ -836,13 +857,13 @@ private class SSLCert {
- returns: a representation security object to be used with
*/
init(key: SecKeyRef) {
public init(key: SecKeyRef) {
self.key = key
}
}
private class SSLSecurity {
var validatedDN = true //should the domain name be validated?
public class SSLSecurity {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
@@ -856,10 +877,11 @@ private class SSLSecurity {
- returns: a representation security object to be used with
*/
convenience init(usePublicKeys: Bool = false) {
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
let certs = paths.reduce([SSLCert]()) { (var certs: [SSLCert], path: String) -> [SSLCert] in
let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in
var certs = certs
if let data = NSData(contentsOfFile: path) {
certs.append(SSLCert(data: data))
}
@@ -877,12 +899,13 @@ private class SSLSecurity {
- returns: a representation security object to be used with
*/
init(certs: [SSLCert], usePublicKeys: Bool) {
public init(certs: [SSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
let pubKeys = certs.reduce([SecKeyRef]()) { (var pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
var pubKeys = pubKeys
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
@@ -896,7 +919,8 @@ private class SSLSecurity {
self.isReady = true
}
} else {
let certificates = certs.reduce([NSData]()) { (var certificates: [NSData], cert: SSLCert) -> [NSData] in
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
}
@@ -915,7 +939,7 @@ private class SSLSecurity {
- returns: if the key was successfully validated
*/
func isValid(trust: SecTrustRef, domain: String?) -> Bool {
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
@@ -1010,7 +1034,8 @@ private class SSLSecurity {
- 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 certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in
var certificates = certificates
let cert = SecTrustGetCertificateAtIndex(trust, index)
certificates.append(SecCertificateCopyData(cert!))
return certificates
@@ -1028,7 +1053,8 @@ private class SSLSecurity {
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (var keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
var keys = keys
let cert = SecTrustGetCertificateAtIndex(trust, index)
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
keys.append(key)