PieSocket SDK for iOS
PieSocket SDK for iOS
PieSocket offers Channels Swift SDK for easy integration into Xcode projects for iPhone, iPad and Mac cross-platform applications.
This SDK is a Swift Library and it can be used as a standalone WebSocket client in any Swift project.
Channels SDK implements auto-reconnections among other best WebSocket practices.
Following is an example of how to subscribe to events in Swift.
Getting started
Create an Xcode project and follow the steps below to add the SDK in your project.
Add Package
Import the github repository into your Xcode project.
- In your Xcode project, go to File > Add packages
- Enter https://github.com/piesocket/websocket-swift-client in the search box
- Click "Add package"
Usage
You are now ready to import PieSocket Channels in your application.
import Channels
Copy
Initialize PieSocket
Define your API Key, Cluster ID and pass it to PieSocket class.
Get your API key and Cluster ID here: Create PieSocket account
let options: PieSocketOptions = PieSocketOptions();
options.setClusterId(clusterId: "demo");
options.setApiKey(apiKey: "VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");
let piesocket: PieSocket = PieSocket(pieSocketOptions: options);
To see the full list of available configuration options,
See: PieSocket Configuration Options
A setter methtod is available on the PieSocketOptions class for all the options listed in the linked page.
Subscribe to a Channel
Subscribe to a Channel with PieSocket's managed WebSocket server.
let channel: Channel = piesocket.join(roomId: "chat-room");
Here chat-room is what we call a roomId. You need this ID to publish messages from your server.
Listen to an event
You can attach multiple listeners to an event by using the code below multiple times. All listeners will be called when the event is fired.
channel.listen(eventName: "new_message", callback: {event in
print(event.getData())
})
There are system events like system:connected, system:member_joined, etc. You can listen to these events to build a beautiful realtime-connected experience.
See a list of all system events here: All system events
Remove an event listener
.listen method returns a String ID for every registered listener. You can use the same listener ID to remove a listener.
channel.removeListener(eventName: "new_message", callbackId: listenerId)
Remove all event listeners
To stop listening for an event, and remove all of the listeners, use the following method.
channel.removeAllListeners(eventName: "new_message")
Publish Events
Use the publish method to publish an event from the client itself.
You must enable client-to-client communication setting for the PieSocket cluster to make this work, in new clusters it is enabled by default.
channel.listen(eventName: "system:connected", callback: {event in
//Channel is connected
//Construct an event
let newMessage = PieSocketEvent(event: "new_message")
newMessage.setData(data: "Hello world!")
//Publish the event
channel.publish(event: newMessage)
})
Developers usually publish events from the backend-server.
See: How to publish events from server
Room members
You can see who is in a room, get system:member_joined to fire and track when people leave by enabling Presence features in a room.
options.setPresence(presence: true)
List all members
To get a list containing all members of the room, use the following code
let members: [AnyObject?] = channel.getAllMembers()
Same is possible from your server, see the REST API section
Get current member
To get information about the current member, use following code
let member: AnyObject? = channel.getCurrentMember()
Copy
User Authentication
PieSocket lets you block un-authorized connections and identify users with the help of JWT authentication tokens.
To learn more, like how to set an User ID, what are Private Channels, etc.
See the: Authentication guide
Set Authentication Endpoint
Set an Authentication URL which generates and responds with JWT tokens. Channels SDK makes a POST request to this URL with Channel information, everytime an user tries to connect to a private room.
options.setAuthEndpoint(authEndpoint: "https://mywebsite.com/generate-jwt")
Optional, add headers to the authEndpoint request
var headers : [String: String] = [String: String]()
headers["Accept"] = "application/json"
headers["Content-type"] = "application/json"
options.setAuthHeaders(authHeaders: headers)
The URL should respond with following JSON on successful authentications.
{"auth":"*************"}
Set JWT Token
To skip the authEndpoint call, and set the JWT yourself, use following method.
options.setJwt(jwt: "*****************");
Leave a Channel
To unsubscribe from a Channel and close the ongoing WebSocket connection, use following code.
All event listeners on this Channel will be removed.
piesocket.leave(roomId: "chat-room")
Stand-alone Usage
You can use the SDK to connect to third party WebSocket servers. Skip, the configuration part and create a Channel instance as shown below.
You will miss out on features like Private Channels, Presence Channels, Multiple Rooms, etc. Stick to PieSocket's managed WebSockets to save upto 60% costs.
let channel: Channel = Channel(webSocketURL: "wss://example.com", enabledLogs: true);
