PubNub Titanium SDK 7.1.1
Unsupported SDK
PubNub no longer supports this SDK but you are welcome to contribute.
Get code
Download a copy from https://github.com/pubnub/javascript/blob/master/dist/titanium/pubnub.js into your resources folder of your Titanium App.
Initialize PubNub
PubNub Javascript SDK 7.1.1 has a distribution for Titanium which allows you to integrate PubNub to your mobile apps for iOS, Android, and Mobile Web.
After downloading the source code and put this into the correct folder you can create an instance with simple lines of code in your app.js
file.
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
var PubNub = require('pubnub');
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE'
});
That's it, you are ready to start using PubNub JS SDK
Hello World Example
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
var PubNub = require('pubnub');
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE'
});
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel : "hello_world",
message : {
title: "greeting",
description: "hello world!"
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
}
pubnub.addListener({
status: function (st) {
if (st.category === "PNConnectedCategory") {
publishSampleMessage();
}
},
message: function (m) {
console.log(m.message.title);
console.log(m.message.description);
},
presence: function (ps) {
console.log(ps);
}
});
pubnub.subscribe({
channels: ['hello_world']
});
Copy and paste examples
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform Access Manager administrative operations from this Titanium V4 instance.
Important
It is not a best practice to include the secretKey
in client-side code for security reasons.
When you init with secretKey
, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
Note
Set restore
to true
to allow catch-up on front-end applications.
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
var pubnub = new PubNub({
subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
publishKey: 'YOUR PUBLISH KEY HERE',
uuid: "myUniqueUUID",
ssl: true
});
Listeners
Adding Listeners
A listener lets you to catch up real time messages, get presence and status information if you do not want to use the getMessage
, getPresence
, getStatus
methods. Remember add a listener before subscribing a channel.
pubnub.addListener({
message: function(m) {
// handle message
var channelName = m.channel; // The channel for which the message belongs
var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = m.timetoken; // Publish timetoken
var msg = m.message; // The Payload
var publisher = m.publisher; //The Publisher
},
presence: function(p) {
// handle presence
var action = p.action; // Can be join, leave, state-change or timeout
var channelName = p.channel; // The channel for which the message belongs
var occupancy = p.occupancy; // No. of users connected with the channel
var state = p.state; // User State
var channelGroup = p.subscription; // The channel group or wildcard subscription match (if exists)
var publishTime = p.timestamp; // Publish timetoken
var timetoken = p.timetoken; // Current timetoken
var uuid = p.uuid; // UUIDs of users who are connected with the channel
},
signal: function(s) {
// handle signal
var channelName = s.channel; // The channel for which the signal belongs
var channelGroup = s.subscription; // The channel group or wildcard subscription match (if exists)
var pubTT = s.timetoken; // Publish timetoken
var msg = s.message; // The Payload
var publisher = s.publisher; //The Publisher
},
status: function(s) {
var affectedChannelGroups = s.affectedChannelGroups; // The channel groups affected in the operation, of type array.
var affectedChannels = s.affectedChannels; // The channels affected in the operation, of type array.
var category = s.category; //Returns PNConnectedCategory
var operation = s.operation; //Returns PNSubscribeOperation
var lastTimetoken = s.lastTimetoken; //The last timetoken used in the subscribe request, of type long.
var currentTimetoken = s.currentTimetoken; //The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
var subscribedChannels = s.subscribedChannels; //All the current subscribed channels, of type array.
}
});
Removing Listeners
var existingListener = {
message: function() {
}
}
pubnub.removeListener(existingListener);
Listener status events
Category | Description |
---|---|
PNNetworkUpCategory | The SDK detected that the network is online. |
PNNetworkDownCategory | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
PNAccessDeniedCategory | Access Manager permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with a bad response error because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish a connection to PubNub due to a timeout. |
PNRequestMessageCountExceedCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |
Time
Call time()
to verify the client connectivity to the origin:
pubnub.time(function(status, response) {
if (status.error) {
console.log(status.error);
} else {
console.log(response.timetoken);
}
});
Subscribe
Subscribe (listen on) a channel:
pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Publish
Publish a message to a channel:
pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
);
Here Now
Get occupancy of who's here now
on the channel by UUID:
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
pubnub.hereNow(
{
channels: ["my_channel"],
channelGroups : ["my_channelGroup"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
console.log(status);
console.log(response);
}
);
Presence
Subscribe to real-time Presence events, such as join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
pubnub.addListener({
presence: function(m) {
console.log(m);
},
message: function(message) {
console.log(message)
}
});
pubnub.subscribe({
channels: ["my_channel"],
withPresence: true
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
History
Retrieve published messages from archival storage:
Note
Requires that the Message Persistence
add-on is enabled for your key. How do I enable add-on features for my keys? - see https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
pubnub.history(
{
channel: 'my_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
function (status, response) {
console.log(response);
}
);
Unsubscribe
Stop subscribing (listening) to a channel:
pubnub.unsubscribe({
channels: ['my_channel']
})
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.