Compare commits

...
9 Commits
7 changed files with 94 additions and 85 deletions

No files matched your search

+4 -4
View File
@@ -29,8 +29,8 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
NSLog(@"connected");
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
[socket emitWithAckObjc:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
[socket emit:@"echo" withItems:@[@"echo test"]];
[socket emitWithAck:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
NSLog(@"Got ack");
});
}];
@@ -103,9 +103,9 @@ Methods
1. `on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - 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. `onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
3. `emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
4. `emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
4. `emit(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
6. `emitWithAckObjc(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
6. `emitWithAck(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "2.0.6"
s.version = "2.1.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -12,7 +12,7 @@ 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 => 'v2.0.6' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.1.0' }
s.source_files = "SocketIOClientSwift/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
+40 -23
View File
@@ -39,6 +39,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
@@ -157,7 +158,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
if params != nil {
let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" ").invertedSet
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
@@ -210,12 +211,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
self.waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
self.doRequest(req)
}
@@ -256,8 +257,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
return
} else if !self!.closed && self!.polling {
self?.doPoll()
}
}.resume()
}}.resume()
}
private func flushProbeWait() {
@@ -299,12 +299,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
self.postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
@@ -540,22 +540,19 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
return
} else {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
where self.client != nil {
// println("sending \(data)")
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
} else if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
where self.client != nil {
// println("sending \(data)")
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
@@ -646,6 +643,9 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
}
/**
Write a message, independent of transport.
*/
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
@@ -662,6 +662,23 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
}
/**
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
*/
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
if let pType = PacketType(rawValue: type) {
var arr = ContiguousArray<NSData>()
if data != nil {
for d in data! {
arr.append(d as! NSData)
}
}
self.write(msg, withType: pType, withData: arr)
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
+2 -3
View File
@@ -280,7 +280,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
/**
Same as emit, but meant for Objective-C
*/
public func emitObjc(event:String, withItems items:[AnyObject]) {
public func emit(event:String, withItems items:[AnyObject]) {
if !self.connected {
return
}
@@ -305,7 +305,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAckObjc(event:String, withItems items:[AnyObject]) -> OnAckCallback {
public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback {
if !self.connected {
return self.createOnAck(event, items: items)
}
@@ -490,7 +490,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
return
}
}
+38 -45
View File
@@ -62,7 +62,7 @@ final class SocketPacket: Printable {
}
}
}
init(type:PacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
@@ -71,19 +71,19 @@ final class SocketPacket: Printable {
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
if self.placeholders == self.currentPlace {
return true
}
self.binary.append(data)
self.currentPlace++
if self.placeholders == self.currentPlace {
self.currentPlace = 0
return true
@@ -91,14 +91,14 @@ final class SocketPacket: Printable {
return false
}
}
func createMessageForEvent(event:String) -> String {
let message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = PacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
@@ -114,7 +114,7 @@ final class SocketPacket: Printable {
}
} else {
self.type = PacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
@@ -129,16 +129,16 @@ final class SocketPacket: Printable {
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
self.type = PacketType.ACK
if nsp == "/" {
msg = "3\(self.id!)["
} else {
@@ -146,70 +146,63 @@ final class SocketPacket: Printable {
}
} else {
self.type = PacketType.BINARY_ACK
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String
message += ","
continue
message += jsonString! as String + ","
} else if arg is String {
message += "\"\(arg)\","
} else if arg is NSNull {
message += "null,"
} else {
message += "\(arg),"
}
if arg is String {
message += "\"\(arg)\""
message += ","
continue
}
message += "\(arg)"
message += ","
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String {
if let num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
}
if let str = self.data?[i] as? String, num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
@@ -219,19 +212,19 @@ final class SocketPacket: Printable {
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
+3 -3
View File
@@ -103,11 +103,11 @@ class SocketParser {
}
}
if buf.toInt() == nil || arr[i] != "-" {
if let holders = buf.toInt() where arr[i] == "-" {
placeholders = holders
} else {
NSLog("Error parsing \(str)")
return nil
} else {
placeholders = buf.toInt()!
}
}
+5 -5
View File
@@ -368,13 +368,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
CFHTTPMessageAppendBytes(response.takeUnretainedValue(), buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response.takeUnretainedValue()) != 101 {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
let headers: NSDictionary = cfHeaders.takeRetainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true