Socket.io iOS and OSX Client compatible with v1.0 and later

Overview

SocketIO-Kit Logo SocketIO-Kit

⚠️ This project is no longer maintained. Please use the official framework Socket.IO-Client-Swift.

SocketIO-Kit is a Socket.io iOS client with type safe, clean syntax and speed in mind. WebSocket is the only transport that is implemented and it uses SwiftWebSocket.

Carthage compatible Version Build Status GitHub license

Installation

Carthage

github "ricardopereira/SocketIO-Kit"

Then run carthage update.

Follow the current instructions in Carthage's README for up to date installation instructions.

CocoaPods

To install it, simply add the following line to your Podfile:

pod "SocketIOKit"

You will also need to make sure you're opting into using frameworks:

use_frameworks!

Then run pod install with CocoaPods 0.36 or newer.

Manually

Download the project and copy the SocketIO-Kit folder into your project and use the Source files. You need Runes v2.0.0 (Swift 1.2) framework to run SocketIO-Kit because it uses infix operators for monadic functions and you need SwiftWebSocket v0.1.18 (Swift 1.2).

There is no need for import SocketIOKit when manually installing.

Requirements

  • iOS 8.0+ / Mac OS X 10.10+
  • Xcode 6.3 (Swift 1.2)

⚠️ Swift 2.0 version, please use branch Swift2.

Usage

import SocketIOKit

// Type safety events
enum AppEvents: String, Printable {
    case ChatMessage = "chat message"
    case GetImage = "getimage"
    case Image = "image"
    
    var description: String {
        return self.rawValue
    }
}

// Mutable
var socket: SocketIO<AppEvents>!
socket = SocketIO(url: "http://localhost:8000/")

// or 
// Immutable
let socket = SocketIO<AppEvents>(url: "http://localhost:8000/")

socket.on(.ConnectError) {
    switch $0 {
    case .Failure(let error):
        println(error)
    default:
        break
    }
}.on(.TransportError) {
    switch $0 {
    case .Failure(let error):
        println("WebSocket error: \(error)")
    default:
        break
    }
}.on(.Connected) { result in
    println("Connected")
    socket.emit(.ChatMessage, withMessage: "I'm iOS")
}.on(.Disconnected) { result in
    switch result {
    case .Message(let reason):
        println("Disconnected: \(reason)")
    default:
        break
    }
}

socket.on(.ChatMessage) {
    switch $0 {
    case .Message(let message):
        println("Remote: \(message)")
    default:
        println("Not supported")
    }
}

socket.connect()

Options

socket = SocketIO(url: "http://localhost:8001/", withOptions: SocketIOOptions().namespace("/gallery"))

Examples

Retrieving an image

// NodeJS Server
var io = require('socket.io')(http)
var fs = require('fs')

io.on('connection', function(socket) {
  socket.on('getimage', function(msg) {
    // Image
    fs.readFile(__dirname + '/image.png', function(err, buf){
      // It's possible to embed binary data within arbitrarily-complex objects
      socket.emit('image', { image: true, buffer: buf.toString('base64') });
    });
  });
});
// SocketIO-Kit Client
socket.on(.Image) {
    switch $0 {
    case .JSON(let json):
        if let image = json["buffer"] as? String >>- SocketIOUtilities.base64EncodedStringToUIImage {
            println(image)
        }
    default:
        println("Not supported")
    }
}

Working with structs

struct ImageInfo: SocketIOObject {
    
    let buffer: String
    
    init(buffer: String) {
        self.buffer = buffer
    }
    
    init(dict: NSDictionary) {
        self.init(buffer: dict["buffer"] as! String) //Force casts should be avoided!
    }
    
    var asDictionary: NSDictionary {
        return ["buffer": buffer]
    }
    
}
// Example using ImageInfo
socket.on(.Image) {
    switch $0 {
    case .JSON(let json):
        let imageInfo = ImageInfo(dict: json) //<---
        
        if let image = imageInfo.buffer >>- SocketIOUtilities.base64EncodedStringToUIImage {
            println(image)
        }
    default:
        println("Not supported")
    }
}

Working with classes

class Person: SocketIOObject {
    
    let name: String
    
    init(name: String) {
        self.name = name
    }
    
    convenience required init(dict: NSDictionary) {
        self.init(name: dict["name"] as! String) //Force casts should be avoided!
    }
    
    var asDictionary: NSDictionary {
        return ["name": name]
    }
    
}
// Example sending John instance
let john = Person(name: "John")

socket.emit(.Login, withObject: john)

Features

To implement
  • Reconnect automatically
  • Complete documentation
  • Test on iOS 7.0+ and Mac OS X 10.9+
  • BDD Tests

Debugging

You can opt into seeing messages by supplying the DEBUG flag. Just add -D DEBUG in Build Settings > Swift Compiler - Custom Flags: Other Swift Flags.

Contributing

See the CONTRIBUTING document. Thank you, contributors!

Author

Ricardo Pereira, @ricardopereiraw

You might also like...
Easy-to-use ICMP Ping for iOS (and maybe OSX)

CDZPinger Easy-to-use ICMP ping for iOS - just create a CDZPinger and you delegate gets a callback every second with the average ping time. Installati

A lightweight, one line setup, iOS / OSX network debugging library! 🦊
A lightweight, one line setup, iOS / OSX network debugging library! 🦊

Netfox provides a quick look on all executed network requests performed by your iOS or OSX app. It grabs all requests - of course yours, requests from

WKZombie is an iOS/OSX web-browser without a graphical user interface.
WKZombie is an iOS/OSX web-browser without a graphical user interface.

WKZombie is a Swift framework for iOS/OSX to navigate within websites and collect data without the need of User Interface or API, also known as Headless browser. It can be used to run automated tests / snapshots and manipulate websites using Javascript.

Twitter-Client - A twitter client that allow users to view tweets on their iphone

Project 3 - Twitter Client Name of your app is a basic twitter app to read your

SSH and SFTP client for iOS
SSH and SFTP client for iOS

Parrot.Flo SSH and SFTP client for iOS https://parrot-flo.site BUG ? Please Submit new issue Contact me Hey ? do you want ask about all my tools ? you

This generic SOAP client allows you to access web services using a your iOS app, Mac OS X app and AppleTV app.
This generic SOAP client allows you to access web services using a your iOS app, Mac OS X app and AppleTV app.

This generic SOAP client allows you to access web services using a your iOS app, Mac OS X app and Apple TV app. With this Framework you can create iPh

An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS
A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS Built by Tijme Gommers – Buy me a coffee via P

Passepartout is a non-official, user-friendly OpenVPN® client for iOS and macOS.
Passepartout is a non-official, user-friendly OpenVPN® client for iOS and macOS.

Passepartout Passepartout is a non-official, user-friendly OpenVPN® client for iOS and macOS. Overview All profiles in one place Passepartout lets you

Comments
  • Disconnection

    Disconnection

    I am trying out the library and cannot understand why I get unexpected disconnections from the client that I cannot debug. The server (socket.io 1.3.5) gives me a disconnection warning, but on my iOS device the on(.Disconnected)() function never gets called. Any idea if this is an issue? The disconnection happens after a short time (some 20/30 sec) of inactivity on the socket.

    bug 
    opened by chasseurmic 8
  • Is it possible to connect with query parameters?

    Is it possible to connect with query parameters?

    In my current project socket clients are connected with "query {Authorization: etc} in web console : Object {transport: "polling", Authorization: "Bearer ..... I tried to add a method "query" the same way like to "namespace" added "withOptions: SocketIOOptions().namespace ", but this option does not work for me

    where I am wrong?

    opened by losedges 3
  • Errors in Security.swift file

    Errors in Security.swift file

    There are several errors in Security.swift. How to resolve this. How come in the file list there are no file "Security.swift" and "WebSocket.swift" however when I downloaded, it has those.

    I am using swift 2.0

    help wanted 
    opened by satyamub 8
  • One callback for multiple events

    One callback for multiple events

    Something similar to:

    socket.on([.ConnectError, .TransportError]) {
        switch $0 {
        case .Failure(let error):
            println(error)
        default:
            break
        }
    }
    
    enhancement 
    opened by ricardopereira 0
Releases(v2.0.1)
Owner
Ricardo Pereira
Passionate about #iOS, #latteart and #personalfinance
Ricardo Pereira
Conforming WebSocket (RFC 6455) client library for iOS and Mac OSX

SwiftWebSocket Conforming WebSocket (RFC 6455) client library for iOS and Mac OS

null 0 Dec 24, 2021
Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.

BlueSocket Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux. Prerequisites Swift Swift Open Source swift-5.1

Kitura 1.3k Dec 26, 2022
Asynchronous socket networking library for Mac and iOS

CocoaAsyncSocket CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for macOS, iOS, and tvOS. The classes are described

Robbie Hanson 12.3k Jan 8, 2023
DispatchSource based socket framework written in pure Swift

SwiftDSSocket Overview SwiftDSSocket is a purely swift based asynchronous socket framework built atop DispatchSource. Function signatures are pretty m

Yi Huang 65 Nov 15, 2022
MVVM project to show AQI of cities via web socket

Air Quality Monitoring Application Swift project with JSON parsing using codable About the application The app consists of live realtime data from the

Pran Kishore 0 Nov 27, 2021
This app is using web-socket for realtime updation of aqi for dedicated inidan cities.

CityWiseAQI This app is using web-socket for realtime updation of aqi for dedicated inidan cities. We're following MVVM architecture in this app. This

Vipul Kumar 2 Feb 7, 2022
Swift async/await based socket

Socket Swift async/await based socket library Introduction This library exposes an idiomatic Swift API for interacting with POSIX sockets via an async

null 89 Dec 29, 2022
Securely synchronize any CareKit 2.1+ based app to a Parse Server Cloud. Compatible with parse-hipaa.

ParseCareKit Use at your own risk. There is no promise that this is HIPAA compliant and we are not responsible for any mishandling of your data This f

Network Reconnaissance Lab 31 Nov 24, 2022
Websockets in swift for iOS and OSX

Starscream is a conforming WebSocket (RFC 6455) library in Swift. Features Conforms to all of the base Autobahn test suite. Nonblocking. Everything ha

Dalton 7.5k Jan 4, 2023
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 1.5k Dec 28, 2022