Compare commits

...
78 Commits
Author SHA1 Message Date
Erik 2cae405d29 try and avoid bad engine states 2015-03-26 13:15:43 -04:00
Erik f008f116a6 fix socketio/socket.io-client-swift#27 2015-03-26 10:13:30 -04:00
Erik 9512c8b9ac change api 2015-03-25 12:02:45 -04:00
Erik b0020997c4 don't use default arg 2015-03-25 11:59:03 -04:00
Erik ce7c9c2c15 bump version 2015-03-25 11:52:55 -04:00
Erik 90f50a1c7e add missing file 2015-03-25 11:51:55 -04:00
Erik 182ba0017b fix nuclearace/Socket.IO-Client-Swift#12 better closing 2015-03-25 11:50:25 -04:00
Erik 5b897ddfea indentation 2015-03-24 14:13:21 -04:00
Erik 78aba627a2 bump version 2015-03-24 11:17:29 -04:00
Erik 9044de53d9 fix socketio/socket.io-client-swift#25 2015-03-24 11:05:03 -04:00
Erik 61ad14f23b refactor remaking packets 2015-03-23 11:34:28 -04:00
Erik 4c7b3175ca bump version 2015-03-22 14:41:15 -04:00
Erik 5533545adb performance 2015-03-22 13:19:53 -04:00
Erik 8fa8944672 fix for no args acks 2015-03-22 11:05:56 -04:00
Erik dee508c0f7 fix race condition 2015-03-22 11:02:31 -04:00
Erik 4de422e7f1 tweaks 2015-03-22 09:53:25 -04:00
Erik 4629565aaf clean up 2015-03-22 08:39:24 -04:00
Erik 8b893ad85e refactor 2015-03-21 18:16:09 -04:00
Erik 6985efd7fb Regular ack doesn't matter 2015-03-20 20:52:34 -04:00
Erik 6ac69d1c2d fix for acks 2015-03-20 20:51:06 -04:00
Erik b8b12313fa Merge branch 'master' into performance 2015-03-20 20:25:53 -04:00
Erik 5388084c79 seems to be on par with the native js-client most of the time 2015-03-20 20:24:59 -04:00
Erik Little 48bcada835 Update SocketEngineClient.swift 2015-03-20 20:22:31 -04:00
Erik cf65f56a1d fix namespaces 2015-03-20 16:05:51 -04:00
Erik 18b8f992d9 Tweaks for performance 2015-03-20 15:23:38 -04:00
Erik 2837c7c42c bump version 2015-03-20 10:54:52 -04:00
Erik 4832be5c8a better parsing 2015-03-20 10:51:26 -04:00
Erik cbc59d6004 fix race condition 2015-03-19 14:13:03 -04:00
Erik 72d5c07de1 refactor 2015-03-19 14:04:02 -04:00
Erik 54b2da8395 work on redesign 2015-03-19 13:22:58 -04:00
Erik Little 5175791513 Update README.md 2015-03-19 11:07:16 -04:00
Erik 2f82de9502 bump version 2015-03-19 08:37:10 -04:00
Erik fd3dbee71c fixes 2015-03-19 08:23:43 -04:00
Erik 911cac9c23 work on parser 2015-03-18 19:54:51 -04:00
Erik d13d185011 work on parser 2015-03-18 19:21:04 -04:00
Erik 66aaa52120 bump version 2015-03-18 18:25:05 -04:00
Erik 5b180a0a6d fix socketio/socket.io-client-swift#20, change objc api 2015-03-18 18:04:43 -04:00
Erik 0ca13c5496 update readme 2015-03-18 13:57:20 -04:00
Erik 1a5487fec5 Merge branch 'auth' 2015-03-18 13:27:06 -04:00
Erik 89ae9bd349 handle utf8 in polling better 2015-03-18 13:05:39 -04:00
Erik c67e7a3003 work on socketio/socket.io-client-swift#11 2015-03-18 09:19:22 -04:00
Erik 472ba50058 bump version 2015-03-18 09:15:13 -04:00
Erik ab77d7260e work on socketio/socket.io-client-swift#17 2015-03-17 23:57:31 -04:00
Erik ac31b4a788 hopefully fix nuclearace/Socket.IO-Client-Swift#27 2015-03-17 12:12:30 -04:00
Erik 7d08f962d5 fix socketio/socket.io-client-swift#16 2015-03-16 20:49:02 -04:00
Erik 2712461044 fix #26 2015-03-16 17:58:12 -04:00
Erik 44e2781076 #11 2015-03-16 13:24:25 -04:00
Erik fea16879e1 Receive doubly encoded utf8 in polling until https://github.com/Automattic/engine.io/issues/315 is fixed properly 2015-03-16 13:12:37 -04:00
Erik Little e932d0a26b Fix copypasta 2015-03-16 11:53:14 -04:00
Erik 6e84950c05 API changed, change version 2015-03-16 11:49:10 -04:00
Erik 90187aa458 fix convenience constructor. Bump version 2015-03-16 11:47:42 -04:00
Erik 68da96f37d fix for objc 2015-03-16 09:23:21 -04:00
Erik ffd92d7bb4 Merge branch 'timeouts' 2015-03-16 09:22:32 -04:00
Erik c103734035 work on parsing stuff 2015-03-15 23:41:01 -04:00
Erik 2022f282c9 add no timeout 2015-03-14 19:46:03 -04:00
Erik d75457f397 Merge branch 'master' into timeouts 2015-03-14 19:12:09 -04:00
Erik bb6bd2b4ca fix race condition in polling 2015-03-14 19:09:54 -04:00
Erik c177671112 work on #23 2015-03-14 14:11:32 -04:00
Erik 2cc68aead6 Don't poll on sendPollMessage 2015-03-13 09:51:53 -04:00
Erik 1f05bde09b small tweaks 2015-03-13 09:09:37 -04:00
Erik 5b019a91c5 start refactoring 2015-03-12 17:54:17 -04:00
Erik a28e924b04 forgot one 2015-03-12 16:53:11 -04:00
Erik f7bf9d4e6b bump version 2015-03-12 16:34:36 -04:00
Erik 37537de213 change visibility of socketioclient members 2015-03-12 16:34:08 -04:00
Erik 8e7c8444d3 set socket sid 2015-03-12 13:44:55 -04:00
Erik 74939f1cea fixes 2015-03-12 13:38:06 -04:00
Erik ab5cccce85 fix binary in dictionaries 2015-03-12 11:38:45 -04:00
Erik 58362f6352 clean up readme 2015-03-12 10:27:37 -04:00
Erik abbd8e6a67 update 2015-03-12 10:19:59 -04:00
Erik Little 3ba793acf1 Merge pull request #8 from banjun/readme-cocoapods
[README] add CocoaPods in Installation section
2015-03-12 10:19:27 -04:00
banjun ea20dc809e [README] add CocoaPods in Installation section 2015-03-12 22:58:00 +09:00
Erik 3e5fe4009c Really update it 2015-03-12 09:33:59 -04:00
Erik a84aa31489 update podspec 2015-03-12 09:32:12 -04:00
Erik 8f7f43f83e add osx 2015-03-12 09:31:27 -04:00
Erik 30cd0bd6cd update thing 2015-03-12 09:17:49 -04:00
Erik Little ac2bc13b11 Merge pull request #7 from banjun/cocoapods
CocoaPods podspec for v1.1.0
2015-03-12 09:08:17 -04:00
banjun 33f3ef4846 add podspec for v1.1.0 and LICENSE 2015-03-12 19:59:49 +09:00
Erik 2e451e5185 trim more 2015-03-11 18:05:25 -04:00
13 changed files with 1361 additions and 1216 deletions

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
The MIT License (MIT)
Copyright (c) 2014-2015 Erik Little
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.
This library makes use of the following third party libraries:
Starscream
----------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
+51 -40
View File
@@ -7,24 +7,53 @@ For Swift 1.2 use the 1.2 branch.
Installation
============
Manually (iOS 7+)
-----------------
1. Copy the SwiftIO folder into your Xcode project!
CocoaPods 0.36.0 or later (iOS 8+)
------------------
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 1.3.2' # Or latest version
```
Install pods:
```
$ pod install
```
Import in your swift file:
```swift
import Socket_IO_Client_Swift
```
API
===
Constructor
Constructors
-----------
`init(socketURL: String, opts:[String: AnyObject]? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values. See example)
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values. See example)
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
Methods
-------
1. `socket.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. `socket.onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
3. `socket.emit(event:String, args:AnyObject...)` - Sends a message. Can send multiple args.
4. `socket.emitObjc(event:String, args:[AnyObject])` - `emit` for Objective-C
5. `socket.emitWithAck(event:String, args:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
6. `socket.emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler` - `emitWithAck` for Objective-C.
3. `socket.emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
4. `socket.emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
5. `socket.emitWithAck(event:String, _ items:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
6. `socket.emitWithAckObjc(event:String, withItems items:[AnyObject]) -> SocketAckHandler` - `emitWithAck` for Objective-C.
7. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `socket.close()` - Closes the socket. Once a socket is closed it should not be reopened.
9. `socket.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.
Events
------
@@ -39,11 +68,12 @@ Example
```swift
// opts can be omitted, will use default values
let socket = SocketIOClient(socketURL: "https://localhost:8080", opts: [
"reconnects": true, // default true
"reconnectAttempts": 5, // default -1 (infinite tries)
"reconnectWait": 5, // default 10
"reconnects": true, // Default is true
"reconnectAttempts": 5, // Default is -1 (infinite tries)
"reconnectWait": 5, // Default is 10
"nsp": "swift", // connects to the specified namespace. Default is /
"forcePolling": true // if true, the socket will only use XHR polling, default is false (polling/WebSockets)
"forcePolling": true, // if true, the socket will only use XHR polling, Default is false (polling/WebSockets)
"cookies": nil // An array of NSHTTPCookies. Passed during handshake. Default is nil
])
// Called on every event
@@ -71,7 +101,13 @@ socket.on("ackEvent") {data, ack in
println("Got ackEvent")
}
socket.emitWithAck("ackTest", "test").onAck {data in
// data is an array
if let int = data?[1] as? Int {
println("Got int")
}
// You can specify a custom timeout interval. 0 means no timeout.
socket.emitWithAck("ackTest", "test").onAck(0) {data in
println(data?[0])
}
@@ -84,44 +120,19 @@ socket.on("jsonTest") {data, ack in
}
}
// Event items are passed by an array
socket.on("multipleItems") {data, ack in
if data == nil {
return
}
if let str = data![0] as? String {
println(str)
}
if let arr = data![1] as? [Int] {
println(arr)
}
if let obj = data![4] as? NSDictionary {
println(obj["test"])
}
}
// Connecting
socket.connect()
// Sending binary
socket.emit("testData", [
"data": "Hello World".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!,
"test": true])
```
Objective-C Example
===================
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" opts:nil];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
NSLog(@"connected");
[socket emitObjc:@"echo" :@[@"echo test"]];
[[socket emitWithAckObjc:@"ackack" :@[@"test"]] onAck:^(NSArray* data) {
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
[[socket emitWithAckObjc:@"ackack" withItems:@[@"test"]] onAck:0 withCallback:^(NSArray* data) {
NSLog(@"Got data");
}];
}];
+19
View File
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "1.4.2"
s.summary = "Socket.IO-client for Swift"
s.description = <<-DESC
Socket.IO-client for Swift.
Supports ws/wss/polling connections and binary.
For socket.io 1.0+ and Swift 1.1.
DESC
s.homepage = "https://github.com/socketio/socket.io-client-swift"
s.license = { :type => 'MIT' }
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 => 'v1.4.2' }
s.source_files = "SwiftIO/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
+23 -3
View File
@@ -29,19 +29,39 @@ public typealias AckCallback = (NSArray?) -> Void
@objc public class SocketAckHandler {
let ackNum:Int!
let event:String!
var acked = false
var callback:AckCallback?
weak var socket:SocketIOClient?
init(event:String, ackNum:Int = 0) {
init(event:String, ackNum:Int = 0, socket:SocketIOClient) {
self.ackNum = ackNum
self.event = event
self.socket = socket
}
func onAck(callback:AckCallback) {
public func onAck(timeout:UInt64, withCallback callback:AckCallback) {
self.callback = callback
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
if !self!.acked {
self?.executeAck(["No ACK"])
self?.socket?.removeAck(self!)
}
}
}
}
func executeAck(data:NSArray?) {
dispatch_async(dispatch_get_main_queue()) {[cb = self.callback] in
dispatch_async(dispatch_get_main_queue()) {[weak self, cb = self.callback] in
self?.acked = true
cb?(data)
return
}
+186 -149
View File
@@ -24,19 +24,16 @@
import Foundation
// This is used because in Swift 1.1, turning on -O causes a
// memory access violation in SocketEngine#parseEngineMessage
private var fixSwift:AnyObject?
extension String {
private var length:Int {
return countElements(self)
}
}
private typealias PollWaitQueue = [() -> Void]
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private enum PacketType: String {
public enum PacketType: String {
case OPEN = "0"
case CLOSE = "1"
case PING = "2"
@@ -46,27 +43,33 @@ private enum PacketType: String {
case NOOP = "6"
}
class SocketEngine: NSObject, WebSocketDelegate {
unowned let client:SocketIOClient
public class SocketEngine: NSObject, WebSocketDelegate {
unowned let client:SocketEngineClient
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create(
"emitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create(
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineParseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create(
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineHandleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
private var forcePolling = false
private var pingTimer:NSTimer?
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = PollWaitQueue()
private let session:NSURLSession!
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
var connected = false
var connected:Bool {
return self._connected
}
var cookies:[NSHTTPCookie]?
var pingInterval:Int?
var polling:Bool {
return self._polling
@@ -79,16 +82,28 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
var ws:WebSocket?
init(client:SocketIOClient, forcePolling:Bool = false) {
public init(client:SocketEngineClient, forcePolling:Bool, withCookies cookies:[NSHTTPCookie]?) {
self.client = client
self.forcePolling = forcePolling
self.cookies = cookies
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: nil, delegateQueue: self.workQueue)
}
func close() {
public func close(#fast:Bool) {
self.pingTimer?.invalidate()
self.send(PacketType.CLOSE.rawValue)
self.closed = true
if self.polling {
self.write("", withType: PacketType.CLOSE, withData: nil)
self.client.didForceClose("Disconnect")
} else {
self.ws?.disconnect()
if fast {
self.client.didForceClose("Fast Disconnect")
}
}
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
@@ -107,7 +122,7 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
}
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
var url = "\(self.client.socketURL)/socket.io/?transport="
var urlPolling:String
var urlWebSocket:String
@@ -142,42 +157,55 @@ class SocketEngine: NSObject, WebSocketDelegate {
return (urlPolling, urlWebSocket)
}
private func doFastUpgrade() {
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
self._websocket = true
self._polling = false
self.fastUpgrade = false
self.flushProbeWait()
}
private func doPoll() {
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
if self.websocket || self.waitingForPoll || !self.connected {
return
}
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
req.timeoutInterval = 0.0
self.waitingForPoll = true
self.doRequest(self.parsePollingMessage)
}
private func doRequest(callback:(String) -> Void) {
if !self.polling {
return
}
let req = NSURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil {
if self!.polling {
self?.handlePollingFailed(err)
self?.handlePollingFailed(err.localizedDescription)
}
return
}
// println(data)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// println(str)
dispatch_async(self!.parseQueue) {[weak self] in
if self == nil {
return
}
self?.parsePollingMessage(str)
return
}
dispatch_async(self!.parseQueue) {callback(str)}
}
self?.waitingForPoll = false
self?.doPoll()
if self!.fastUpgrade {
self?.doFastUpgrade()
return
} else if !self!.closed {
self?.doPoll()
}
}.resume()
}
@@ -189,7 +217,7 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
for waiter in self!.probeWait {
waiter()
self?.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self?.probeWait.removeAll(keepCapacity: false)
@@ -217,22 +245,21 @@ class SocketEngine: NSObject, WebSocketDelegate {
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
req.HTTPMethod = "POST"
req.setValue("application/html-text", forHTTPHeaderField: "Content-Type")
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
// NSLog("posting: \(postStr)")
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
self.waitingForPost = true
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil && self!.polling {
self?.handlePollingFailed(err)
self?.handlePollingFailed(err.localizedDescription)
return
}
@@ -255,41 +282,48 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
// A poll failed, tell the client about it
// We check to see if we were closed by the server first
private func handlePollingFailed(reason:NSError?) {
if !self.client.reconnecting {
self.connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
private func handlePollingFailed(reason:String) {
self._connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
if !self.closed && !self.client.reconnecting {
self.client.pollingDidFail(reason)
} else if !self.client.reconnecting {
self.client.didForceClose(reason)
}
}
func open(opts:[String: AnyObject]? = nil) {
if self.waitingForPost || self.waitingForPoll || self.websocket || self.connected {
assert(false, "We're in a bad state, this shouldn't happen.")
public func open(opts:[String: AnyObject]? = nil) {
if self.connected {
fatalError("Engine tried to open while connected")
}
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
self.closed = false
let (urlPolling, urlWebSocket) = self.createURLs(opts)
self.urlPolling = urlPolling
self.urlWebSocket = urlWebSocket
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
reqPolling.allHTTPHeaderFields = headers
}
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
var err2:NSError?
if self == nil {
return
} else if err != nil || data == nil {
self?.handlePollingFailed(err)
self?.handlePollingFailed(err.localizedDescription)
return
}
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var mutString = RegexMutable(dataString)
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
let parsed:[String]? = dataString["(\\d*):(\\d)(\\{.*\\})?"].groups()
if parsed == nil || parsed?.count != 4 {
return
@@ -304,13 +338,12 @@ class SocketEngine: NSObject, WebSocketDelegate {
return
}
self?.connected = true
if let json = NSJSONSerialization.JSONObjectWithData(jsonData!,
options: NSJSONReadingOptions.AllowFragments, error: &err2) as? NSDictionary {
if let sid = json["sid"] as? String {
// println(json)
self?.sid = sid
self?._connected = true
if !self!.forcePolling {
self?.ws = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
@@ -363,7 +396,7 @@ class SocketEngine: NSObject, WebSocketDelegate {
length += chr
} else {
if length == "" || testLength(length, &n) {
self.handlePollingFailed(nil)
self.handlePollingFailed("Error parsing XHR message")
return
}
@@ -379,10 +412,8 @@ class SocketEngine: NSObject, WebSocketDelegate {
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
fixSwift = msg
if fixSwift is String {
self?.parseEngineMessage(fixSwift as String)
}
self?.parseEngineMessage(msg)
return
}
}
@@ -393,21 +424,19 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
private func parseEngineData(data:NSData) {
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
return
}
}
private func parseEngineMessage(var message:String) {
// println(message!)
var strMessage = RegexMutable(message)
// We should upgrade
if strMessage == "3probe" {
self.upgradeTransport()
return
// NSLog("Engine got message: \(message)")
if self.polling {
fixDoubleUTF8(&message)
}
let type = strMessage["^(\\d)"].groups()?[1]
let type = message["^(\\d)"].groups()?[1]
if type != PacketType.MESSAGE.rawValue {
// TODO Handle other packets
@@ -420,17 +449,27 @@ class SocketEngine: NSObject, WebSocketDelegate {
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
// println("sending \(data)")
self.client.parseBinaryData(data)
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseBinaryData(data)
return
}
}
return
} else if type == PacketType.NOOP.rawValue {
self.doPoll()
return
}
if message == PacketType.CLOSE.rawValue {
// do nothing
} else if type == PacketType.PONG.rawValue {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
} else if type == PacketType.CLOSE.rawValue {
if self.polling {
self.client.didForceClose("Disconnect")
}
return
}
// println("Got something idk what to do with")
@@ -439,9 +478,11 @@ class SocketEngine: NSObject, WebSocketDelegate {
// Remove message type
message.removeAtIndex(message.startIndex)
// println("sending \(messageString)")
self.client.parseSocketMessage(message)
dispatch_async(self.client.handleQueue) {[weak self] in
self?.client.parseSocketMessage(message)
return
}
}
private func probeWebSocket() {
@@ -450,33 +491,12 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
}
func send(msg:String, datas:[NSData]? = nil) {
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
return {
if self == nil || !self!.connected {
return
}
if self!.websocket {
// println("sending ws: \(msg):\(datas)")
self?.sendWebSocketMessage(msg, withType: PacketType.MESSAGE, datas: datas)
} else {
// println("sending poll: \(msg):\(datas)")
self?.sendPollMessage(msg, withType: PacketType.MESSAGE, datas: datas)
}
}
}
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
if self!.probing {
self?.probeWait.append(_send(msg, datas))
} else {
_send(msg, datas)()
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if self.probing {
self.probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
self.write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
@@ -488,40 +508,40 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
}
private func sendPollMessage(msg:String, withType type:PacketType, datas:[NSData]? = nil) {
// println("Sending: poll: \(msg) as type: \(type.rawValue)")
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
// println("Sending poll: \(msg) as type: \(type.rawValue)")
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
}
}
}
if waitingForPost {
self.doPoll()
return
} else {
self.flushWaitingForPost()
}
if !self.waitingForPost {
self.flushWaitingForPost()
}
}
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
// println("Sending: ws: \(str) as type: \(type.rawValue)")
self.ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.writeData(data!)
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
// println("Sending ws: \(str) as type: \(type.rawValue)")
self.ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.writeData(data!)
}
}
}
}
}
// Starts the ping timer
@@ -532,35 +552,52 @@ class SocketEngine: NSObject, WebSocketDelegate {
self.pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!), target: self,
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!),
target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
private func upgradeTransport() {
if self.websocketConnected {
// Do a fast upgrade
self.fastUpgrade = true
self.probing = false
self._websocket = true
self.waitingForPoll = false
self._polling = false
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
self.flushProbeWait()
self.sendPollMessage("", withType: PacketType.NOOP)
}
}
func websocketDidConnect(socket:WebSocket) {
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
if self!.websocket {
// NSLog("writing ws: \(msg):\(data)")
self?.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
// NSLog("writing poll: \(msg):\(data)")
self?.sendPollMessage(msg, withType: type, datas: data)
}
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
self.probing = true
self.probeWebSocket()
}
func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self._connected = false
self._websocket = false
self._polling = true
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
@@ -569,11 +606,11 @@ class SocketEngine: NSObject, WebSocketDelegate {
}
}
func websocketDidReceiveMessage(socket:WebSocket, text:String) {
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text)
}
func websocketDidReceiveData(socket:WebSocket, data:NSData) {
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
}
+41
View File
@@ -0,0 +1,41 @@
//
// SocketEngineClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/19/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 SocketEngineClient {
var handleQueue:dispatch_queue_attr_t! {get}
var emitQueue:dispatch_queue_attr_t! {get}
var reconnecting:Bool {get}
var socketURL:String {get}
var secure:Bool {get}
func didForceClose(reason:String)
func parseSocketMessage(msg:String)
func parseBinaryData(data:NSData)
func pollingDidFail(err:String)
func webSocketDidCloseWithCode(code:Int, reason:String, wasClean:Bool)
func webSocketDidFailWithError(error:NSError)
}
-255
View File
@@ -1,255 +0,0 @@
//
// Event.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/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
class SocketEvent {
let justAck:Bool!
var ack:Int?
var args:AnyObject!
lazy var currentPlace = 0
lazy var datas = [NSData]()
var event:String!
var placeholders:Int!
init(event:String, args:AnyObject?, placeholders:Int = 0, ackNum:Int? = nil, justAck:Bool = false) {
self.event = event
self.args = args
self.placeholders = placeholders
self.ack = ackNum
self.justAck = justAck
}
func addData(data:NSData) -> Bool {
func checkDoEvent() -> Bool {
if self.placeholders == self.currentPlace {
return true
} else {
return false
}
}
if checkDoEvent() {
return true
}
self.datas.append(data)
self.currentPlace++
if checkDoEvent() {
self.currentPlace = 0
return true
} else {
return false
}
}
class func createMessageForEvent(event:String, withArgs args:[AnyObject],
hasBinary:Bool, withDatas datas:Int = 0, toNamespace nsp:String?, wantsAck ack:Int? = nil) -> String {
var message:String
var jsonSendError:NSError?
if !hasBinary {
if nsp == nil {
if ack == nil {
message = "2[\"\(event)\""
} else {
message = "2\(ack!)[\"\(event)\""
}
} else {
if ack == nil {
message = "2/\(nsp!),[\"\(event)\""
} else {
message = "2/\(nsp!),\(ack!)[\"\(event)\""
}
}
} else {
if nsp == nil {
if ack == nil {
message = "5\(datas)-[\"\(event)\""
} else {
message = "5\(datas)-\(ack!)[\"\(event)\""
}
} else {
if ack == nil {
message = "5\(datas)-/\(nsp!),[\"\(event)\""
} else {
message = "5\(datas)-/\(nsp!),\(ack!)[\"\(event)\""
}
}
}
return self.completeMessage(message, args: args)
}
class func createAck(ack:Int, withArgs args:[AnyObject], withAckType ackType:Int,
withNsp nsp:String, withBinary binary:Int = 0) -> String {
var msg:String
if ackType == 3 {
if nsp == "/" {
msg = "3\(ack)["
} else {
msg = "3/\(nsp),\(ack)["
}
} else {
if nsp == "/" {
msg = "6\(binary)-\(ack)["
} else {
msg = "6\(binary)-/\(nsp),\(ack)["
}
}
return self.completeMessage(msg, args: args, ack: true)
}
private class func completeMessage(var message:String, args:[AnyObject], ack:Bool = false) -> String {
var err:NSError?
if args.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in args {
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
}
if arg is String {
message += "\"\(arg)\""
message += ","
continue
}
message += "\(arg)"
message += ","
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
private func fillInArray(arr:NSArray) -> NSArray {
var newArr = [AnyObject](count: arr.count, repeatedValue: 0)
// println(arr)
for i in 0..<arr.count {
if let nest = arr[i] as? NSArray {
newArr[i] = self.fillInArray(nest)
} else if let dict = arr[i] as? NSDictionary {
newArr[i] = self.fillInDict(dict)
} else if let str = arr[i] as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
newArr[i] = self.datas[num[1].toInt()!]
} else {
newArr[i] = arr[i]
}
} else {
newArr[i] = arr[i]
}
}
return newArr
}
private func fillInDict(dict:NSDictionary) -> NSDictionary {
var newDict = [String: AnyObject]()
for (key, value) in dict {
newDict[key as String] = value
// If the value is a string we need to check
// if it is a placeholder for data
if let str = value as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
newDict[key as String] = self.datas[num[1].toInt()!]
} else {
newDict[key as String] = str
}
} else if let nestDict = value as? NSDictionary {
newDict[key as String] = self.fillInDict(nestDict)
} else if let arr = value as? NSArray {
newDict[key as String] = self.fillInArray(arr)
}
}
return newDict
}
func fillInPlaceholders(_ args:AnyObject = true) -> AnyObject {
if let dict = args as? NSDictionary {
return self.fillInDict(dict)
} else if let arr = args as? NSArray {
return self.fillInArray(args as NSArray)
} else if let string = args as? String {
if string == "~~\(self.currentPlace)" {
return self.datas[0]
}
} else if args is Bool {
// We have multiple items
// Do it live
let argsAsArray = "[\(self.args)]"
if let parsedArr = SocketIOClient.parseData(argsAsArray) as? NSArray {
var returnArr = [AnyObject](count: parsedArr.count, repeatedValue: 0)
for i in 0..<parsedArr.count {
if let str = parsedArr[i] as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
returnArr[i] = self.datas[num[1].toInt()!]
} else {
returnArr[i] = str
}
} else if let arr = parsedArr[i] as? NSArray {
returnArr[i] = self.fillInArray(arr)
} else if let dict = parsedArr[i] as? NSDictionary {
returnArr[i] = self.fillInDict(dict)
} else {
returnArr[i] = parsedArr[i]
}
}
return returnArr
}
}
return false
}
}
+5 -7
View File
@@ -28,12 +28,10 @@ public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias AnyHandler = (event:String, items:AnyObject?)
public typealias AckEmitter = (AnyObject...) -> Void
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int) -> AckEmitter {
func emitter(items:AnyObject...) {
socket.emitAck(num, withData: items, withAckType: type)
}
return emitter
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {
socket.emitAck(num, withData: items)
}
class SocketEventHandler {
@@ -48,7 +46,7 @@ class SocketEventHandler {
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!, type!) : nil)
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
return
}
}
+37
View File
@@ -0,0 +1,37 @@
//
// SocketFixUTF8.swift
// Socket.IO-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(inout name:String) {
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)!
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
}
File diff suppressed because it is too large. Load diff
+236
View File
@@ -0,0 +1,236 @@
//
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/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
enum SocketPacketType: Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init(str:String) {
if let int = str.toInt() {
self = SocketPacketType(rawValue: int)!
} else {
self = SocketPacketType(rawValue: 4)!
}
}
}
class SocketPacket {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:SocketPacketType?
init(type:SocketPacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as String
}
func addData(data:NSData) -> Bool {
func checkDoEvent() -> Bool {
if self.placeholders == self.currentPlace {
return true
} else {
return false
}
}
if checkDoEvent() {
return true
}
self.binary.append(data)
self.currentPlace++
if checkDoEvent() {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
var message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = SocketPacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = SocketPacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
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
}
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()!]
} else {
newArr[i] = str
}
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} 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
}
}
}
+258
View File
@@ -0,0 +1,258 @@
//
// SocketParser.swift
// Socket.IO-Swift
//
// 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
private let shredder = SocketParser.PacketShredder()
class SocketParser {
// Translation of socket.io-parser#deconstructPacket
private class PacketShredder {
var buf = ContiguousArray<NSData>()
func shred(data:AnyObject) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
return placeholder
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = shred(arr[i])
}
return newArr
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in newDict {
newDict[key as NSCopying] = shred(value)
}
return newDict
} else {
return data
}
}
func deconstructPacket(packet:SocketPacket) {
if packet.data == nil {
return
}
var data = packet.data!
for i in 0..<data.count {
if data[i] is NSArray || data[i] is NSDictionary {
data[i] = shred(data[i])
} else if let bin = data[i] as? NSData {
data[i] = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
}
}
packet.data = data
packet.binary = buf
buf.removeAll(keepCapacity: true)
}
}
// Translation of socket.io-client#decodeString
class func parseString(str:String) -> SocketPacket? {
let arr = Array(str)
let type = String(arr[0])
if arr.count == 1 {
return SocketPacket(type: SocketPacketType(str: type))
}
var id = nil as Int?
var nsp = ""
var i = 0
var placeholders = -1
if type == "5" || type == "6" {
var buf = ""
while arr[++i] != "-" {
buf += String(arr[i])
if i == arr.count {
break
}
}
if buf.toInt() == nil || arr[i] != "-" {
NSLog("Error parsing \(str)")
return nil
} else {
placeholders = buf.toInt()!
}
}
if arr[i + 1] == "/" {
while ++i < arr.count {
let c = arr[i]
if c == "," {
break
}
nsp += String(c)
}
}
if i + 1 >= arr.count {
return SocketPacket(type: SocketPacketType(str: type),
nsp: nsp, placeholders: placeholders, id: id)
}
let next = String(arr[i + 1])
if next.toInt() != nil {
var c = ""
while ++i < arr.count {
if let int = String(arr[i]).toInt() {
c += String(arr[i])
} else {
--i
break
}
}
id = c.toInt()
}
if i + 1 < arr.count {
let d = String(arr[++i...arr.count-1])
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = SocketParser.parseData(noPlaceholders) as [AnyObject]
return SocketPacket(type: SocketPacketType(str: type), data: data,
nsp: nsp, placeholders: placeholders, id: id)
}
return nil
}
// Parses data for events
class func parseData(data:String) -> AnyObject? {
var err:NSError?
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.AllowFragments, error: &err)
if err != nil {
// println(err)
return nil
}
return parsed
}
class func parseForEmit(packet:SocketPacket) {
shredder.deconstructPacket(packet)
}
// Parses messages recieved
class func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
if stringMessage == "" {
return
}
func checkNSP(nsp:String) -> Bool {
if nsp == "" && socket.nsp != "/" {
return true
} else {
return false
}
}
let p = parseString(stringMessage) as SocketPacket!
if p.type == SocketPacketType.EVENT {
if checkNSP(p.nsp) {
return
}
socket.handleEvent(p.getEvent(), data: p.data, isInternalMessage: false, wantsAck: p.id, withAckType: 3)
} else if p.type == SocketPacketType.ACK {
if checkNSP(p.nsp) {
return
}
socket.handleAck(p.id!, data: p.data)
} else if p.type == SocketPacketType.BINARY_EVENT {
if checkNSP(p.nsp) {
return
}
socket.waitingData.append(p)
} else if p.type == SocketPacketType.BINARY_ACK {
if checkNSP(p.nsp) {
return
}
p.justAck = true
socket.waitingData.append(p)
} else if p.type == SocketPacketType.CONNECT {
if p.nsp == "" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
} else if p.type == SocketPacketType.DISCONNECT {
socket.didForceClose("Got Disconnect")
}
}
// Handles binary data
class func parseBinaryData(data:NSData, socket:SocketIOClient) {
// NSLog(data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros))
if socket.waitingData.count == 0 {
NSLog("Got data when not remaking packet")
return
}
let shouldExecute = socket.waitingData[0].addData(data)
if !shouldExecute {
return
}
let packet = socket.waitingData.removeAtIndex(0)
packet.fillInPlaceholders()
if !packet.justAck {
socket.handleEvent(packet.getEvent(), data: packet.data,
wantsAck: packet.id, withAckType: 6)
} else {
socket.handleAck(packet.id!, data: packet.data)
}
}
}
+46 -166
View File
@@ -16,11 +16,10 @@ import Foundation
var swiftRegexCache = [String: NSRegularExpression]()
public class SwiftRegex: NSObject, BooleanType {
var target: NSString
var target:String
var regex: NSRegularExpression
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
@@ -44,12 +43,12 @@ public class SwiftRegex: NSObject, BooleanType {
}
final var targetRange: NSRange {
return NSRange(location: 0,length: target.length)
return NSRange(location: 0,length: countElements(target.utf16))
}
final func substring(range: NSRange) -> NSString! {
final func substring(range: NSRange) -> String? {
if ( range.location != NSNotFound ) {
return target.substringWithRange(range)
return (target as NSString).substringWithRange(range)
} else {
return nil
}
@@ -63,19 +62,19 @@ public class SwiftRegex: NSObject, BooleanType {
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
}
public func match(options: NSMatchingOptions = nil) -> String! {
return substring(range(options: options)) as String
public func match(options: NSMatchingOptions = nil) -> String? {
return substring(range(options: options))
}
public func groups(options: NSMatchingOptions = nil) -> [String]! {
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
public func groups(options: NSMatchingOptions = nil) -> [String]? {
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
}
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) as String! {
if let group = substring(match.rangeAtIndex(groupno)) {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
@@ -87,19 +86,23 @@ public class SwiftRegex: NSObject, BooleanType {
}
}
public subscript(groupno: Int) -> String! {
public subscript(groupno: Int) -> String? {
get {
return groups()[groupno]
return groups()?[groupno]
}
set(newValue) {
if let mutableTarget = target as? NSMutableString {
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult( match,
inString: target as String, offset: 0, template: newValue )
mutableTarget.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
}
} else {
SwiftRegex.failure("Group modify on non-mutable")
if newValue == nil {
return
}
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult(match,
inString: target as String, offset: 0, template: newValue!)
let mut = NSMutableString(string: target)
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
target = mut as String
}
}
}
@@ -120,24 +123,23 @@ public class SwiftRegex: NSObject, BooleanType {
}
public func matches(options: NSMatchingOptions = nil) -> [String] {
return matchResults(options: options)!.map( { self.substring($0.range) as String } )
return matchResults(options: options)!.map( { self.substring($0.range)!})
}
public func allGroups(options: NSMatchingOptions = nil) -> [[String]] {
return matchResults(options: options)!.map { self.groupsForMatch($0) }
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
return matchResults(options: options)!.map {self.groupsForMatch($0)}
}
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults(options: options)! {
out[substring(match.rangeAtIndex(1)) as String] =
substring(match.rangeAtIndex(2))
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
}
return out
}
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
options:NSMatchingOptions = nil) -> NSMutableString {
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0
@@ -145,63 +147,21 @@ public class SwiftRegex: NSObject, BooleanType {
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
let matchRange = match.range
out.appendString( self.substring( NSRange(location:pos, length:matchRange.location-pos) ) as String )
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
out.appendString( substitution(match, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString( substring( NSRange(location:pos, length:targetRange.length-pos) ) as String )
out.appendString(substring( NSRange(location:pos, length:targetRange.length-pos))!)
if let mutableTarget = target as? NSMutableString {
mutableTarget.setString(out as String)
return mutableTarget
} else {
SwiftRegex.failure("Modify on non-mutable")
return out
}
}
/* removed Beta6
public func __conversion() -> Bool {
return doesMatch()
return out as String
}
public func __conversion() -> NSRange {
return range()
}
public func __conversion() -> String {
return match()
}
public func __conversion() -> [String] {
return matches()
}
public func __conversion() -> [[String]] {
return allGroups()
}
public func __conversion() -> [String:String] {
return dictionary()
}
*/
public var boolValue: Bool {
return doesMatch()
}
}
extension NSString {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
}
}
extension NSString {
public subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern)
}
}
extension String {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
@@ -214,18 +174,14 @@ extension String {
}
}
public func RegexMutable(string: NSString) -> NSMutableString {
return NSMutableString(string:string as String)
}
public func ~= (left: SwiftRegex, right: String) -> NSMutableString {
public func ~= (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: nil)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
public func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
@@ -235,95 +191,19 @@ public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: (String) -> String) -> NSMutableString {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range) as String)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]) -> String) -> NSMutableString {
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range)!)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: nil)
}
// my take on custom threading operators from
// http://ijoshsmith.com/2014/07/05/custom-threading-operator-in-swift/
private let _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
public func | (left: () -> Void, right: () -> Void) {
dispatch_async(_queue) {
left()
dispatch_async(dispatch_get_main_queue(), right)
}
}
public func | <R> (left: () -> R, right: (result:R) -> Void) {
dispatch_async(_queue) {
let result = left()
dispatch_async(dispatch_get_main_queue(), {
right(result:result)
})
}
}
// dispatch groups { block } & { block } | { completion }
public func & (left: () -> Void, right: () -> Void) -> [() -> Void] {
return [left, right];
}
public func & (left: [() -> Void], right: () -> Void) -> [() -> Void] {
var out = left
out.append( right )
return out
}
public func | (left: [() -> Void], right: () -> Void) {
let group = dispatch_group_create()
for block in left {
dispatch_group_async(group, _queue, block)
}
dispatch_group_notify(group, dispatch_get_main_queue(), right)
}
// parallel blocks with returns
public func & <R> (left: () -> R, right: () -> R) -> [() -> R] {
return [left, right]
}
public func & <R> (left: [() -> R], right: () -> R) -> [() -> R] {
var out = left
out.append( right )
return out
}
public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
let group = dispatch_group_create()
var results = Array<R!>()
for t in 0..<left.count {
results += [nil]
}
for t in 0..<left.count {
//dispatch_retain(group)
dispatch_group_enter(group)
dispatch_async(_queue, {
results[t] = left[t]()
dispatch_group_leave(group)
//dispatch_release(group)
})
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
right(results: results)
})
}, options: nil)
}