MegaBits / SIOSocket

Realtime iOS application framework (client) http://socket.io
MIT License
494 stars 80 forks source link

Swift documentation #30

Open markstreich opened 9 years ago

markstreich commented 9 years ago

As someone new to iOS development and Swift, I could really use more Swift guidance and/or links to example code in the Readme.md

For example:

vasarhelyia commented 9 years ago

@markstreich check out my project using SIOSocket with Swift: https://github.com/brewfactory/BrewMobile

markstreich commented 9 years ago

Thanks @vasarhelyia! I got it working using BrewFactory as an example.

I'll suggest some documentation below based on what I learned.

Adding SIOSocket to a Swift project using CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
link_with ['AppName', 'AppNameTests']
pod 'SIOSocket', '~> 0.2.0'
#import <SIOSocket/SIOSocket.h>

Sample Swift Code

This assumes you have the Socket.io Chat Example Server running on your local machine. It will create a socket.io connection with SIOSocket, login, and emit a message.

In the browser you will see: screen shot 2014-12-04 at 11 19 47 am

Output in Xcode should look something like this: screen shot 2014-12-04 at 11 20 12 am

File contents for: ViewController.swift

import UIKit

let host = "http://localhost:3000/"
let username = "swiftbot"
let message = "Hello World"

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.connectToHost()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func connectToHost() {
        SIOSocket.socketWithHost(host, reconnectAutomatically: true, attemptLimit: 0, withDelay: 1, maximumDelay: 5, timeout: 20, response: {socket in
            socket.onConnect = {
                println("Connected to \(host)")
                socket.emit("add user", args: [username])
            }
            socket.on("login", callback: {(AnyObject data) -> Void in
                println(["login": data])
                socket.emit("new message", args: [message])
            })
            socket.onDisconnect = {
                println("Disconnected from \(host)")
            }
        })
    }
}