Objective-CCocoaCocoaiOSCocoa SDK 4.15.8

CocoaPods is a dependency manager and this is by far the easiest and quickest way to get started with PubNub Cocoa SDK! (If you don't have pods installed yet you can check CocoaPods installation section for installation guide).

Be sure you are running CocoaPods 1.0.0 or above! You can install the latest cocoapods gem:

gem install cocoapods

If you’ve already installed you can upgrade to the latest CocoaPods gem using:

gem update cocoapods
Add the PubNub Cocoa SDK folder to your project.
To build the framework as a standalone bundle and integrate into project, perform the following:
  1. Clone the PubNub master repository
    
    git clone git@github.com:pubnub/objective-c.git
    
  2. Navigate to root of the cloned repository
  3. Run the CocoaPods pod install command to pull out all required dependencies
    
    pod install
    
  4. Open the PubNub.xcworkspace from the PubNub repository in Xcode.
  5. Select the Framework or Universal Framework target for target platform and hit Cmd+B to build the selected type of framework.
    Select Framework target

  6. Navigate to the Framework directory and find the Products directory.
    Navigate to Framework bundle

  7. Drag&Drop PubNub.framework bundle from the Products directory to your application.
    Drag & drop Framework bundle

  8. Select the Copy items if needed checkbox and click Finish.
    Copy Framework bundle

  9. Open your project's General tab and scroll to Embedded Binaries.
    Open embedded binaries group Objective C

  10. Click on + and select PubNub.framework file.
    Add Framework bundle to embedded binaries group

 
If the PubNub target has been used, then the framework will be generated only for the selected platform (device or simulator.) If you try to use the framework to compile for another platform, it will crash during run-time! Using the PubNub-Universal build target (which can be used on both device and simulator) will help mitigate any sort of crash scenarios during development.

Now that these steps are complete, let's learn more about how to use the framework in your app.

At this point, you should have the framework added to your application project, we'll need to make your project aware of the PubNub framework.

You need to import the PubNub headers in classes where it will be used.


#import <PubNub/PubNub.h>

To build the framework as a standalone bundle and integrate into project, perform the following:

  1. Install latest Carthage (if required).
  2. Create a Cartfile (any location can be used) or use existing file.
    
    touch Cartfile
  3. Add next line into a Cartfile which will allow to build framework bundles

    
    		github "pubnub/objective-c" ~> 4.1	
  4. Update and rebuild the project's dependencies (update command ensure what latest PubNub client code will be used to build framework). build can be used if frameworks has been built before and it will be much faster because git clone will be skipped.

    
    		carthage update

    Command above will build framework for all configured platforms, but if only one required it can be called like this

    
    		carthage update --platform ios

    Instead of ios can be used: mac, tvos or watchos

  5. Navigate to the Carthage directory and find the Build directory.
  6. Navigate to directory which represent your target platform. For example: iOS

    Navigate to built framework bundle for Carthage

  7. Drag&Drop PubNub.framework bundle from the Products directory to your application.

    Drag & drop Framework bundle for Carthage

  8. Select the Copy items if needed checkbox and click Finish.

    Copy Framework bundle for Carthage

  9. Open your project's General tab and scroll to Embedded Binaries.

    Open embedded binaries group Objective C for Carthage

  10. Click on + and select PubNub.framework file.

    Add Framework bundle to embedded binaries group for Carthage

At this point, you should have the framework added to your application project, we'll need to make your project aware of the PubNub framework.

You need to import the PubNub headers in classes where it will be used.


#import <PubNub/PubNub.h>

View Supported Platforms
Install CocoaPods gem by following the procedure defined under How to Get It.
To add the PubNub SDK to your project with CocoaPods, there are four basic tasks to complete which are covered below:
  1. Create new Xcode project.
  2. Create Podfile in new Xcode project root folder
    touch Podfile
  3. The PubNub client can be added as module (only with a deployment target of OS X 10.9 and above):
    
    source 'https://github.com/CocoaPods/Specs.git'
    platform :osx, "10.9"
    use_frameworks!
    
    target 'application-target-name' do
        pod "PubNub", "~> 4.1"
    end
    		
    If you have any other pods you'd like to include, or if you have other targets you'd to add (like a test target) add those entries to this Podfile as well. See the CocoaPods documentation for more information on Podfile configuration.
  4. Install your pods by running pod install via the command line from the directory that contains your Podfile.

 

 
After installing your Pods, you should only be working within the workspace generated by CocoaPods or specified by you in Podfile. Always open the newly generated workspace file, not the original project file!

 

 

To be able to use PubNub SDK within your application code you need to import it. Import PubNub SDK headers in implementation files for classes where you need to use it using this import statement:

 

#import <PubNub/PubNub.h>

 

 

Add the PNObjectEventListener protocol to AppDelegate in implementation file to anonymous category:
 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.

#import <PubNub/PubNub.h>

@interface AppDelegate () <PNObjectEventListener>

// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic, strong) PubNub *client;

@end
 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.
// Initialize and configure PubNub client instance
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" subscribeKey:@"demo"];
configuration.uuid = @"myUniqueUUID";

self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];

// Subscribe to demo channel with presence observation
[self.client subscribeToChannels: @[@"my_channel"] withPresence:YES];

// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {

    // Handle new message stored in message.data.message
    if (![message.data.channel isEqualToString:message.data.subscription]) {

        // Message has been received on channel group stored in message.data.subscription.
    }
    else {

        // Message has been received on channel stored in message.data.channel.
    }

    NSLog(@"Received message: %@ on channel %@ at %@", message.data.message[@"msg"],
        message.data.channel, message.data.timetoken);
}

// New presence event handling.
- (void)client:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {

    if (![event.data.channel isEqualToString:event.data.subscription]) {

        // Presence event has been received on channel group stored in event.data.subscription.
    }
    else {

        // Presence event has been received on channel stored in event.data.channel.
    }

    if (![event.data.presenceEvent isEqualToString:@"state-change"]) {

        NSLog(@"%@ \"%@'ed\"\nat: %@ on %@ (Occupancy: %@)", event.data.presence.uuid,
            event.data.presenceEvent, event.data.presence.timetoken, event.data.channel,
            event.data.presence.occupancy);
    }
    else {

        NSLog(@"%@ changed state at: %@ on %@ to: %@", event.data.presence.uuid,
            event.data.presence.timetoken, event.data.channel, event.data.presence.state);
    }
}

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

    if (status.operation == PNSubscribeOperation) {

        // Check whether received information about successful subscription or restore.
        if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {

            // Status object for those categories can be casted to `PNSubscribeStatus` for use below.
            PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
            if (subscribeStatus.category == PNConnectedCategory) {

                // This is expected for a subscribe, this means there is no error or issue whatsoever.

                // Select last object from list of channels and send message to it.
                NSString *targetChannel = [client channels].lastObject;
                [self.client publish: @{ @"msg": @"hello" }
                    toChannel: targetChannel withCompletion:^(PNPublishStatus *publishStatus) {

                    // Check whether request successfully completed or not.
                    if (!publishStatus.isError) {

                      // Message successfully published to specified channel.
                    }
                    else {

                      /**
                       Handle message publish error. Check 'category' property to find out
                       possible reason because of which request did fail.
                       Review 'errorData' property (which has PNErrorData data type) of status
                       object to get additional information about issue.

                       Request can be resent using: [publishStatus retry];
                      */
                    }
                }];
            }
            else {

                /**
                 This usually occurs if subscribe temporarily fails but reconnects. This means there was
                 an error but there is no longer any issue.
                 */
            }
        }
        else if (status.category == PNUnexpectedDisconnectCategory) {

            /**
             This is usually an issue with the internet connection, this is an error, handle
             appropriately retry will be called automatically.
             */
        }
        // Looks like some kind of issues happened while client tried to subscribe or disconnected from
        // network.
        else {

            PNErrorStatus *errorStatus = (PNErrorStatus *)status;
            if (errorStatus.category == PNAccessDeniedCategory) {

                /**
                 This means that PAM does allow this client to subscribe to this channel and channel group
                 configuration. This is another explicit error.
                 */
            }
            else {

                /**
                 More errors can be directly specified by creating explicit cases for other error categories
                 of `PNStatusCategory` such as: `PNDecryptionErrorCategory`,
                 `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory`
                 or `PNNetworkIssuesCategory`
                 */
            }
        }
    }
}
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
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 PAM administrative operations from this Cocoa instance.
 

It is not a best practice to include the secret key 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.

 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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" 
																 subscribeKey:@"demo"];
configuration.uuid = @"myUniqueUUID";
self.client = [PubNub clientWithConfiguration:configuration];
 
PubNub instance should be placed as a property in a long-life object (otherwise PubNub instance will be automatically removed as autoreleased object).

@property (nonatomic, strong) PubNub *client;

Listener's class should conform to PNEventsListener protocol to have access to available callbacks.

// Adding listener.
[pubnub addListener:self];


// Callbacks listed below.

- (void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message {
    NSString *channel = message.data.channel; // Channel on which the message has been published
    NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSNumber *timetoken = message.data.timetoken; // Publish timetoken
    id msg = message.data.message; // Message payload
    NSString *publisher = message.data.publisher; // Message publisher
}

- (void)client:(PubNub *)pubnub didReceiveSignal:(PNSignalResult *)signal {
    NSString *channel = message.data.channel; // Channel on which the signal has been published
    NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSNumber *timetoken = message.data.timetoken; // Signal timetoken
    id msg = message.data.message; // Signal payload
    NSString *publisher = message.data.publisher; // Signal publisher
}

- (void)client:(PubNub *)pubnub didReceiveMessageAction:(PNMessageActionResult *)action {
    NSString *channel = action.data.channel; // Channel on which the message has been published
    NSString *subscription = action.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSString *event = action.data.event; // Can be: added or removed
    NSString *type = action.data.action.type; // Message action type
    NSString *value = action.data.action.value; // Message action value
    NSNumber *messageTimetoken = action.data.action.messageTimetoken; // Timetoken of the original message
    NSNumber *actionTimetoken = action.data.action.actionTimetoken; // Timetoken of the message action
    NSString *uuid = action.data.action.uuid; // UUID of user which added / removed message action
}

- (void)client:(PubNub *)pubnub didReceivePresenceEvent:(PNPresenceEventResult *)event {
    NSString *channel = message.data.channel; // Channel on which presence changes
    NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSString *presenceEvent = event.data.presenceEvent; // Can be: join, leave, state-change, timeout or interval
    NSNumber *occupancy = event.data.presence.occupancy; // Number of users subscribed to the channel (not available for state-change event)
    NSNumber *timetoken = event.data.presence.timetoken; // Presence change timetoken
    NSString *uuid = event.data.presence.uuid; // UUID of user for which presence change happened

    // Only for 'state-change' event
    NSDictionary *state = event.data.presence.state; // User state (only for state-change event)

    // Only for 'interval' event
    NSArray<NSString *> *join = event.data.presence.join; // UUID of users which recently joined channel
    NSArray<NSString *> *leave = event.data.presence.leave; // UUID of users which recently leaved channel
    NSArray<NSString *> *timeout = event.data.presence.timeout; // UUID of users which recently timed out on channel
}

- (void)client:(PubNub *)pubnub didReceiveObjectEvent:(PNObjectEventResult *)event {
    NSString *channel = event.data.channel; // Channel to which the event belongs
    NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSString *event = event.data.event; // Can be: set or delete
    NSString *type = event.data.type; // Entity type: channel, uuid or membership
    NSNumber *timestamp = event.data.timestamp; // Event timestamp

    PNChannelMetadata *channelMetadata = event.data.channelMetadata; // Updated channel metadata (only for channel entity type)
    PNUUIDMetadata *uuidMetadata = event.data.uuidMetadata; // Updated channel metadata (only for uuid entity type)
    PNMembership *membership = event.data.membership; // Updated channel metadata (only for membership entity type)
}

- (void)client:(PubNub *)pubnub didReceiveFileEvent:(PNFileEventResult *)event {
    NSString *channel = event.data.channel; // Channel to which file has been uploaded
    NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    id message = event.data.message; // Message added for uploaded file
    NSString *publisher = event.data.publisher; // UUID of file uploader
    NSURL *fileDownloadURL = event.data.file.downloadURL; // URL which can be used to download file
    NSString *fileIdentifier = event.data.file.identifier; // Unique file identifier
    NSString *fileName = event.data.file.name; // Name with which file has been stored remotely
}

- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
    PNStatusCategory category = status.category; // One of PNStatusCategory fields to identify status of operation processing
    PNOperationType operation = status.operation; // One of PNOperationType fields to identify for which operation status received
    BOOL isError = status.isError; // Whether any kind of error happened.
    NSInteger statusCode = status.statusCode; // Related request processing status code
    BOOL isTLSEnabled = status.isTLSEnabled; // Whether secured connection enabled
    NSString *uuid = status.uuid; // UUID which configured for passed client
    NSString *authKey = status.authKey; // Auth key configured for passed client
    NSString *origin = status.origin; // Origin against which request has been sent
    NSURLRequest *clientRequest = status.clientRequest; // Request which has been used to send last request (may be nil)
    BOOL willAutomaticallyRetry = status.willAutomaticallyRetry; // Whether client will try to perform automatic retry

    // Following information available when operation == PNSubscribeOperation, because status is PNSubscribeStatus instance in this case
    PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
    NSNumber *currentTimetoken = subscribeStatus.currentTimetoken; // Timetoken which has been used for current subscribe request
    NSNumber *lastTimeToken = subscribeStatus.lastTimeToken; // Timetoken which has been used for previous subscribe request
    NSArray<NSString *> *subscribedChannels = subscribeStatus.subscribedChannels; // List of channels on which client currently subscribed
    NSArray<NSString *> *subscribedChannelGroups = subscribeStatus.subscribedChannelGroups; // List of channel groups on which client currently subscribed
    NSString *channel = subscribeStatus.data.channel; // Name of channel for which status has been received
    NSString *subscription = subscribeStatus.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
    NSNumber *timetoken = subscribeStatus.data.timetoken; // Timetoken at which event arrived
    NSDictionary *userMetadata = subscribeStatus.data.userMetadata; // Metadata / envelope which has been passed along with event

    // Following information available when isError == YES, because status is PNErrorStatus instance in this case
    PNErrorStatus *errorStatus = (PNErrorStatus *)status;
    id associatedObject = errorStatus.associatedObject; // Data which may contain related information (not decrypted message for example)
    NSArray<NSString *> *erroredChannels = errorStatus.errorData.channels; // List of channels for which error reported (mostly because of PAM)
    NSArray<NSString *> *erroredChannelGroups = errorStatus.errorData.channelGroups; // List of channel groups for which error reported (mostly because of PAM)
    NSString *errorInformation = errorStatus.errorData.information; // Stringified information about error
    id errorData = errorStatus.errorData.data; // Additional error information from PubNub service
}
[pubnub removeListener:self]
CategoriesDescription
PNAcknowledgmentCategoryReported operation request acknowledgment status.
PNAccessDeniedCategoryPAM permission failure.
PNTimeoutCategoryServer didn't respond in time for reported operation request.
PNNetworkIssuesCategoryNo connection to Internet.
PNRequestMessageCountExceededCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNConnectedCategoryThe SDK subscribed to new channels / channel groups.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNDisconnectedCategoryThe SDK unsubscribed from channels / channel groups.
PNUnexpectedDisconnectCategoryThe SDK unexpectedly lost ability to receive live updated from PubNub.
PNRequestURITooLongCategoryReported operation request URI too long (too many channels / channel groups).
PNMalformedFilterExpressionCategoryThe SDK has been configured with malformed filtering expression.
PNMalformedResponseCategoryThe SDK received unexpected PubNub service response.
PNDecryptionErrorCategoryThe SDK unable to decrypt received message using configured cipherKey.
PNTLSConnectionFailedCategoryThe SDK unable to establish secured connection.
PNTLSUntrustedCertificateCategoryThe SDK unable to check certificates trust chain.
Call timeWithCompletion to verify the client connectivity to the origin:
[self.client timeWithCompletion:^(PNTimeResult *result, PNErrorStatus *status) {

	if (!status) {

		// Handle downloaded server time token using: result.data.timetoken
	}
	else {

		/**
		 Handle time token download error. Check 'category' property to find 
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.
		
		 Request can be resent using: [status retry];
		 */
	}
}];
Subscribe (listen on) a channel (it's async!):
/**
 Subscription results arrive to a listener which should implement the
 PNObjectEventListener protocol and be registered as follows:
 */
[self.client addListener:self]; 
[self.client subscribeToChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];
 

// Handle a new message from a subscribed channel
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
    // Reference to the channel group containing the chat the message was sent to
    NSString *subscription = message.data.subscription; 
    NSLog(@"%@ sent message to '%@' at %@: %@", message.data.publisher, message.data.channel, 
			message.data.timetoken, message.data.message);
}

// Handle a subscription status change
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
    
	if (status.operation == PNSubscribeOperation) {
        
		// Check to see if the message is about a successful subscription or restore
		if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {

			// Status object for those categories can be cast to `PNSubscribeStatus` for use below.
			PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
			if (subscribeStatus.category == PNConnectedCategory) {

				// For a subscribe, this is expected, and means there are no errors or issues
			}
			else {
                
				// This usually occurs if there is a transient error. The subscribe fails but
                 // then reconnects, and there is no longer any issue.
			}
		}
		else if (status.category == PNUnexpectedDisconnectCategory) {

			// This is usually an issue with the internet connection.
            // This is an error: handle appropriately, and retry will be called automatically.
		}
		// An issue occurred while the client tried to subscribe,
        // or the client was disconnected from the network
		else {

			PNErrorStatus *errorStatus = (PNErrorStatus *)status;
			if (errorStatus.category == PNAccessDeniedCategory) {

				// PAM prohibited this client from subscribing to this channel and channel group. 
                // This is another explicit error.
			}
			else {
					
				/**
                 You can directly specify more errors by creating explicit cases
                 for other categories of `PNStatusCategory` errors, such as:
                 - `PNDecryptionErrorCategory`
                 - `PNMalformedFilterExpressionCategory`
                 - `PNMalformedResponseCategory`
                 - `PNTimeoutCategory`
                 - `PNNetworkIssuesCategory`
                 */
			}
		}
	}
	else if (status.operation == PNUnsubscribeOperation) {

		if (status.category == PNDisconnectedCategory) {

			// This is the expected category for an unsubscribe.
            // There were no errors in unsubscribing from everything.
		}
	}
	else if (status.operation == PNHeartbeatOperation) {

		/**
		 Heartbeat operations can have errors, so check first for an error.
		 For more information on how to configure heartbeat notifications through the status 
		 PNObjectEventListener callback, refer to
         http://www.pubnub.com/docs/ios-objective-c/api-reference-configuration#configuration_basic_usage
		 */

		if (!status.isError) { /* Heartbeat operation was successful */ }
		else { /* There was an error with the heartbeat operation: handle it here */ }
	}
}

// Handle a new signal from a subscribed channel
- (void)client:(PubNub *)client didReceiveSignal:(PNSignalResult *)signal {
    NSLog(@"%@ sent signal to '%@' at %@: %@", message.data.publisher, message.data.channel, 
          message.data.timetoken, message.data.message);
}

// Handle new object event from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveObjectEvent:(PNObjectEventResult *)event {
    NSLog(@"'%@' has been %@'ed at %@", event.data.type, event.data.event, 
        event.data.timestamp);
}
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 a message to a channel:
[self.client publish: @{@"Dictionary": @[@"with",@"array",@"as", @"value"]} 
		   toChannel: @"pubnub" withCompletion:^(PNPublishStatus *status) {
    
	if (!status.isError) {

		// Message successfully published to specified channel.
	}
	else {

		/**
		 Handle message publish error. Check 'category' property to find 
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
Get occupancy of who's here now on the channel by UUID:
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.
// With PNHereNowUUID client will pull out list of unique identifiers and occupancy information.
[self.client hereNowForChannel: @"my_channel" withVerbosity:PNHereNowUUID
					completion:^(PNPresenceChannelHereNowResult *result, 
								 PNErrorStatus *status) {

	// Check whether request successfully completed or not.
	if (!status) {

		/**
		 Handle downloaded presence information using:
			result.data.uuids - list of uuids.
			result.data.occupancy - total number of active subscribers.
		 */
	}
	else {

		/**
		 Handle presence audit error. Check 'category' property to find
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
Subscribe to realtime 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:
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.
/**
 Subscription process results arrive to listener which should adopt to
 PNObjectEventListener protocol and registered using:
 */
[self.client addListener:self];
[self.client subscribeToPresenceChannels:@[@"my_channel"]];


// New presence event handling.
- (void)client:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {
	
	if (![event.data.channel isEqualToString:event.data.subscription]) {
		
		// Presence event has been received on channel group stored in event.data.subscription.
	}
	else {
		
		// Presence event has been received on channel stored in event.data.channel.
	}
	
	if (![event.data.presenceEvent isEqualToString:@"state-change"]) {
		
		NSLog(@"%@ \"%@'ed\"\nat: %@ on %@ (Occupancy: %@)", event.data.presence.uuid, 
			  event.data.presenceEvent, event.data.presence.timetoken, event.data.channel, 
			  event.data.presence.occupancy);
	}
	else {
		
		NSLog(@"%@ changed state at: %@ on %@ to: %@", event.data.presence.uuid, 
			  event.data.presence.timetoken, event.data.channel, event.data.presence.state);
	}
}
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.
Retrieve published messages from archival storage:
Requires that the Storage and Playback 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-
[self.client historyForChannel: @"my_channel" start:nil end:nil limit:100
				withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {

	if (!status) {

		/**
		 Handle downloaded history using: 
			result.data.start - oldest message time stamp in response
			result.data.end - newest message time stamp in response
			result.data.messages - list of messages
		 */
	}
	else {

		/**
		 Handle message history download error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: [status retry];
		 */
	}
}];
Stop subscribing (listening) to a channel.
/**
 Unsubscription process results arrive to listener which should adopt to
 PNObjectEventListener protocol and registered using:
 */
[self.client addListener:self];
[self.client unsubscribeFromChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
 
	if (status.operation == PNUnsubscribeOperation && status.category == PNDisconnectedCategory) {

		/**
		 This is the expected category for an unsubscribe. This means there was no error in 
		 unsubscribing from everything.
		 */
	}
}
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.