ActionCable is a new WebSockets server being released with Rails 5 which makes it easy to add real-time features to your app

Overview

ActionCableClient

Version License Platform Carthage compatible

ActionCable is a new WebSockets server being released with Rails 5 which makes it easy to add real-time features to your app. This Swift client makes it dead-simple to connect with that server, abstracting away everything except what you need to get going.

Installation

To install, simply:

Cocoapods

Add the following line to your Podfile and run pod install

pod "ActionCableClient"

Carthage

Add the following to your Cartfile and run carthage update as normal.

github "danielrhodes/Swift-ActionCableClient"

Usage

Get Started & Connect

import ActionCableClient

self.client = ActionCableClient(url: URL(string: "ws://domain.tld/cable")!)

// Connect!
client.connect()

client.onConnected = {
    print("Connected!")
}

client.onDisconnected = {(error: Error?) in
    print("Disconnected!")
}

Subscribe to a Channel

// Create the Room Channel
let roomChannel = client.create("RoomChannel") //The channel name must match the class name on the server

// More advanced usage
let room_identifier = ["room_id" : identifier]
let roomChannel = client.create("RoomChannel", identifier: room_identifier, autoSubscribe: true, bufferActions: true)

Channel Callbacks

// Receive a message from the server. Typically a Dictionary.
roomChannel.onReceive = { (JSON : Any?, error : ErrorType?) in
    print("Received", JSON, error)
}

// A channel has successfully been subscribed to.
roomChannel.onSubscribed = {
    print("Yay!")
}

// A channel was unsubscribed, either manually or from a client disconnect.
roomChannel.onUnsubscribed = {
    print("Unsubscribed")
}

// The attempt at subscribing to a channel was rejected by the server.
roomChannel.onRejected = {
    print("Rejected")
}

Perform an Action on a Channel

// Send an action
roomChannel["speak"](["message": "Hello, World!"])

// Alternate less magical way:
roomChannel.action("speak", ["message": "Hello, World!"])

// Note: The `speak` action must be defined already on the server

Authorization & Headers

// ActionCable can be picky about origins, so if you
// need it can be set here.
client.origin = "https://domain.tld/"

// If you need any sort of authentication, you 
// will not have cookies like you do in the browser,
// so set any headers here.
//
// These are available in the `Connection`
// on the server side.

client.headers = [
    "Authorization": "sometoken"
]

Misc

client.onPing = {
    
}

For more documentation, see the wiki

Requirements

Starscream: The underlying WebSocket library.

Author

Daniel Rhodes, [email protected]

License

ActionCableClient is available under the MIT license. See the LICENSE file for more info.

Comments
  • Action Cable on receive method is not called

    Action Cable on receive method is not called

    Hello Daniel am using the action cable, I will explain you the scenario for the onReceive method not called.

    When we start the application then the action cable is working fine, But if I logout from my application and then login from different user then the action cable of onReceive method is not called. I don't understand what happens but if I kill the application and then start it again. Then the action cables onReceive method will work. I don't know what am doing wrong.

    Can you suggest me what I have to do.

    opened by MandeepSingh1 20
  • Channel action fired without errors without internet connection

    Channel action fired without errors without internet connection

    There's something weird. When I call channel.Action without internet connection it doesn't return any error. isSubscribed seems to be true even without internet connection.

    Any idea?

    Update: Seems like the client doesn't detect the lost connection. How can I add ActionCableClient manually to the project to test it?

    What I do is:

    • Connect to action cable
    • Subscribe to channel
    • Kill internet connection
    • Send an action
    • It's sended without issues, channel.action doesn't fire the expected error
    opened by bitomule 8
  • Unable to update to latest version

    Unable to update to latest version

    Hello and thanks for the library! I am having issues updating the library to its latest version - 0.2.1

    Not specifying the version - installs the ActionCableClient to 0.1.4 If I set it as pod 'ActionCableClient', '0.2.1', I get the following error:

    [!] Unable to satisfy the following requirements:
    
    - `ActionCableClient (= 0.2.1)` required by `Podfile`
    
    None of your spec sources contain a spec satisfying the dependency: `ActionCableClient (= 0.2.1)`.
    
    You have either:
     * out-of-date source repos which you can update with `pod repo update`.
     * mistyped the name or version.
     * not added the source repo that hosts the Podspec to your Podfile.
    

    UPDATE: I ended up using pod 'ActionCableClient', :git=> 'https://github.com/danielrhodes/Swift-ActionCableClient', :branch => '0.2.2' which fixed it, it but I'm guessing something is wrong with the default install.

    opened by danipralea 6
  • Authentication Question

    Authentication Question

    What type of headers would I need to set for authentication with this? Do I just need to pass a users.id?

    client.headers = [
        "Authorization": "sometoken"
    ]
    

    Rails Log:

    Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-04-14 18:47:13 +0000
    Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
      ESC[1mESC[36mUser Load (1.3ms)ESC[0m  ESC[1mESC[34mSELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT $1ESC[0m  [["LIMIT", 1]]
    An unauthorized connection attempt was rejected
    Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
    

    XCode Log:

    ActionCableClient.TransmitError.NotConnected
    Connected!
    Disconnected!
    
    opened by daande 6
  • roomChannel.onReceive method not getting called

    roomChannel.onReceive method not getting called

    I am sending two parameters while creating the roomChannel and it is successfully subscribed, so onSubscribed is called but I am not able to receive messages, i.e onReceive method is not getting called. @danielrhodes

    opened by mansishah278 5
  • JSON decoding error for ping in v0.1.5

    JSON decoding error for ping in v0.1.5

    Since version v0.1.5 the ping message fails JSON decoding with: [ActionCableClient] Error decoding message: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

    opened by kh0r 4
  • masked and rsv data is not currently supported

    masked and rsv data is not currently supported

    After the success of login, first try socket connection and success. when I logout and re-login, and connection socket again, I got below:

    ActionCableClient.ConnectionError.ProtocolViolation(Error Domain=WebSocket Code=1002 "masked and rsv data is not currently supported" UserInfo={NSLocalizedDescription=masked and rsv data is not currently supported})

    please help...

    opened by chakery 4
  • minimum deployment target

    minimum deployment target

    pod 'ActionCableClient', :git => 'https://github.com/danielrhodes/Swift-ActionCableClient', :branch => 'swift3'

    Specs satisfying the ActionCableClient (fromhttps://github.com/danielrhodes/Swift-ActionCableClient, branchswift3) dependency were found, but they required a higher minimum deployment target.

    Seems it requires iOS 9.0 Why? Before Swift3, this project supports >= 8.0 right? Current my project support OS >= 8.0

    opened by selfcreator 3
  • update SwiftyJSON dependency to ~> 2.3.2

    update SwiftyJSON dependency to ~> 2.3.2

    In SwiftyJSON version 2.3.2 a method isExists() has been changed to exists() which breaks this library.

    Here is the relevant change: https://github.com/SwiftyJSON/SwiftyJSON/commit/5fc4545c7a5d1fd4a2b3d04964f1bc593c356676

    opened by vaughankg 3
  • Clear channels

    Clear channels

    Is there a way to clear autoSubscribed channels, let say when a user sign out? I can disconnect the websocket, but when I reconnect it when the other user log in, old subscriptions remain. Note that I'm using a Singleton ActionCable Manager, so maybe I should just reset the singleton instance?

    opened by allaire 2
  • onConnect is not being called

    onConnect is not being called

    Hi, I have a this simple connection function

    `func initializeActionCabel() { self.client = ActionCableClient(url: URL(string: "ws://ip.of.my.server:3000.tld/cable")!)

        self.client.willConnect = {
            print("Will Connect")
        }
        
        self.client.onConnected = {
            print("Action Cable Connected!")
            self.channel = self.client.create("ChatChannel")
        }
        
        self.client.onDisconnected = {(error: ConnectionError?) in
            print("Action Cable Disconnected! \(error.debugDescription)")
        }
        
        self.client.onRejected = {
            print("Action Cable Connection Rejected!")
        }
        
        self.client.willReconnect = {
            print("Reconnecting to \(self.client.url)")
            return true
        }
        
        self.client.onPing = {
            print("On Ping")
        }
        
        self.channel?.onSubscribed = {
            print("Subscribed to 'ChatChannel'")
        }
        
        self.channel?.onReceive = {(data: Any?, error: Error?) in
            print("On Receive")
            if let _ = error {
                print(error)
                return
            }
        }
        
        // Connect!
        self.client.connect()
    }`
    

    Problem is: willReconnect and onDisconnected are being called just fine. But onConnected callback is not called ever.

    Can you please comment or see if i'm missing something? Thanks in advance.

    Cheers.

    opened by waleedmahmood 2
  • Crash when server returns a disconnect response

    Crash when server returns a disconnect response

    Our rails server occasionally returns the following response

    {"type":"disconnect","reason":"unauthorized","reconnect":false}"

    This will cause the code to crash on line 112 of JSONSerializer.swift:

                return Message(channelIdentifier: channelIdentifier!,      // <<-- there is no "identifier" member in the response, so channelIdentfier will be nil
                               actionName: messageActionName,
                               messageType: MessageType.message,
                               data: messageValue,
                               error: messageError)
    

    Recommend that the code be fixed to not force-unwrap channelIdentifier and treat the disconnect the same as a reject

    opened by dmorgereth 0
  • Xcode 10.3

    Xcode 10.3

    in Xcode 10.3 - after pod: Downloading dependencies Installing ActionCableClient (0.2.3) Installing Starscream (2.0.4) Generating Pods project Integrating client project

    [!] Please close any current Xcode sessions and use SwiftAcabClient.xcworkspace for this project from now on. Sending stats Pod installation complete! There is 1 dependency from the Podfile and 2 total pods installed.

    - after run xcworkspace: :-1: SWIFT_VERSION '3.0' is unsupported, supported versions are: 4.0, 4.2, 5.0. (in target 'ActionCableClient')

    opened by ValenOnish 3
  • Message not received when app is in background mode

    Message not received when app is in background mode

    Problem in background mode. When the app goes background state Receive message is just stopped and no further updates from peer. It gets active and returns the older messages when I become foreground. This is stopping my integration and looking for alternative SDK. Am I missing anything around to config? ( enabled all background config under capability )

    opened by Sathishobs 1
Releases(v0.2.2)
Owner
Daniel Rhodes
Daniel Rhodes
Fast Websockets in Swift for iOS and OSX

SwiftWebSocket Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX. SwiftWebSocket passes all 521 of the Autobahn's fuzzing tests, incl

Josh Baker 1.5k Dec 27, 2022
🔌 Non-blocking TCP socket layer, with event-driven server and client.

Original authors Honza Dvorsky - http://honzadvorsky.com, @czechboy0 Matthias Kreileder - @matthiaskr1 At the request of the original authors, we ask

Vapor Community 574 Dec 7, 2022
The easy way to use sockets on Apple platforms

SwiftSocket SwiftSocket library provides as easy to use interface for socket based connections on server or client side. Supports both TCP and UDP soc

null 1.6k Jan 3, 2023
An extreme queuing system with high performance for managing all task in app with closure

SwiftyTask An extreme queuing system with high performance for managing all task in app with closure Task Method Tasking of queued closure on GCD (Gra

Albin CR 21 Aug 26, 2021
AQMonitoring - Air Quality Monitoring App to see live AQI and city data/graph in Swift with WebSocket and MVVM architecture

AQMonitoring Air Quality Monitoring App to see live AQI and city data/graph in S

Kajal Nasit 0 Jan 9, 2022
IHTypeWriterLabel - A simple, UILabel subclass which poulates itself as if being typed

IHTypeWriterLabel A simple, UILabel subclass which poulates itself as if being typed. HighLights Written purely in SWIFT. Very simple and lightweight.

Md Ibrahim Hassan 24 May 7, 2019
Tutorials from sparrowcode.io website. You can add new, translate or fix typos. Also you can add your apps from App Store for free.

Tutorials from sparrowcode.io website. You can add new, translate or fix typos. Also you can add your apps from App Store for free.

Sparrow Code 31 Jan 3, 2023
Tutorials from sparrowcode.io website. You can add new, translate or fix typos. Also you can add your apps from App Store for free.

Страницы доступны на sparrowcode.io/en & sparrowcode.io/ru Как добавить свое приложение Добавьте элемент в json /ru/apps/apps.json. Если ваше приложен

Sparrow Code 30 Nov 25, 2022
Discover new programming concepts and more new SwiftUI 2 features in this section

Africa-Zoo One thing is sure, we will discover new programming concepts and more new SwiftUI 2 features in this section. TOPICS ARE COVERED: JSON with

Noye Samuel 2 Nov 8, 2022
This iOS framework allows settings to be in-app in addition to or instead of being in the Settings app.

InAppSettingsKit InAppSettingsKit (IASK) is an open source framework to easily add in-app settings to your iOS or Catalyst apps. Normally iOS apps use

Ortwin Gentz, FutureTap 3.1k Jan 2, 2023
Sync your app's time with server's UTC time

ServerSync for iOS Apps Sometimes your app can't rely on the device's date and time settings being correct. This library will help you calibrate your

null 10 Dec 16, 2021
A replacement for as which runs in constant time instead of O(n) when the conformance is not satisfiedA replacement for as which runs in constant time instead of O(n) when the conformance is not satisfied

ZConform A replacement for as? which runs in constant time instead of O(n) when the conformance is not satisfied. How it works ZConform does a one-tim

Emerge Tools 20 Aug 4, 2022
Ruby Gem for Rails - Easy iTunes In-App Purchase Receipt validation, including auto-renewable subscriptions

Monza is a ruby gem that makes In-App Purchase receipt and Auto-Renewable subscription validation easy. You should always validate receipts on the ser

Gabriel 159 Jan 7, 2023
Simple class to check if app has been cracked, being debugged or enriched with custom dylib

iOS-App-Security-Class Simple class to check if iOS app has been cracked, being debugged or enriched with custom dylib and as well detect jailbroken e

Unhandled Exception 74 Mar 11, 2022
The demo app demonstrates a real-time application using FindSurface to search point clouds, which ARKit provides, for geometry shapes.

FindSurface-GUIDemo-iOS (Swift) CurvSurf FindSurface™ GUIDemo for iOS (Swift) Overview This demo app demonstrates a real-time application using FindSu

CurvSurf 0 Nov 28, 2022
IHKeyboardAvoiding is an elegant solution for keeping any UIView visible when the keyboard is being shown - no UIScrollView required!

IHKeyboardAvoiding An elegant solution for keeping any UIView visible when the keyboard is being shown Requirements IHKeyboardAvoiding Version Objecti

Idle Hands Apps 1.4k Dec 14, 2022
Turbo-iOS base project that's entirely driven from your backend Rails app.

Turbo-iOS base project that's entirely driven from your backend Rails app.

Dale Zak 109 Dec 11, 2022
BottomSheet makes it easy to add custom bottom sheets to your SwiftUI apps.

BottomSheet About BottomSheet BottomSheet makes it easy to add custom bottom sheets to your SwiftUI apps. The result can look like this...or completel

Daniel Saidi 174 Jan 2, 2023
Personal App that turned into "alpha released app"

Muubii Works on macos 11.0 and later* Installation Automatic install (recommended) Open Terminal. Paste the line below, once done check your applicati

Aayush 429 Jan 2, 2023
Personal App that turned into "alpha released app"

Native-Youtube Personal App that turned into "alpha released app" Requirements: MacOS 12.0 or above A working google account Usage Download the univer

Aayush 426 Dec 28, 2022