Creating an iPhone Video Chat App using Parse and Opentok (tokbox)

Creating an iPhone video chat app isn’t rocket science, but there are a lot of intricacies to account for. This tutorial covers the entire purpose of developing such an app from start to finish. It is quite long, so you might want to bookmark it so you can revisit it later.

The end result: The entire project can be downloaded here. You can browse if you want to figure it out for yourself, for those who are interested in a detailed walkthrough, read on.

Video chat is one of the most popular forms of communication on mobile, and is for productivity apps as well as social networking.

So how does one go about building such an app? The question is more of design than of technical implementation when many online services provide a lot of the infrastructure needed.

By the end of this tutorial, our app would look like this:

Yes, that is a monkey chatting with a mammoth. Which is basically what we would be doing communicating with the services composing our app.

The Basics of a video Chat app:

While the top video chat application use their own streaming servers, we will be using a cloud-based solution to handle that part of the equation. Opentok is the service that we’ll be using in this tutorial, and it provides a nice, easy-to-integrate SDK for adding video streaming capabilities to our app.

While Opentok provides their iOS API and iOS SDK with two useful examples of iOS implementation (here and here), there is still one piece left: User management. Opentok provides nice platform for video chat, but between whom? Let’s take a deeper dive into how streaming actually works between users of services like Skype, MSN, and Yahoo video chat.

A streaming server works on fundamentals of an Http web server: In a pretty raw representation, all it recognizes is request and response, without caring who sent it. An Http server does just that. It does not worry about states, userID, password or any such access token mechanism. In other words, session management is absent.

The scenario changes when there arises a need to identify the user, authenticate him, and keep him authenticated during his entire browsing experience. A server needs to remember a user, and whatever other entities that come linked with him. These requirements become more stringent while developing a mobile software like iPhone video chat, where identities are quite crucial – they can make or break the authenticity of your app. In large web portals such as or, dedicated authentication servers generate unique identity for users, and supply application servers with these goodies so that they can track the users until they log out.

To perform its task, a streaming server relies on only one entity to recognize who sent the request and whom to respond – this entity is session ID. It does not recognize or want to care who generated it. As far as it receives a valid sessionID, it keeps replying to streaming requests. And here comes rule of thumb for any chatting app:

Any user with a valid sessionID is, in principle, automatically entitled to view other user’s feed who is also using the same sessionID. Session IDs are of the form:

  1. 2_MX4yNjU5MzIyMn5-VHVlIEFwciAyMyAwMjoxMTo0NCBQRFQgMjAxM34wLjEzMTIwMTYyfg

You probably know where this is going: To keep track of who wants to connect to whom in a more real-worldly way, like we do in Yahoo Messenger or Skype, we need another server that keeps track of users. User management is essential in any social networking app. It depends on you how much you want to do it – you can store big data including address, phone numbers, profile pics and the likes, or you can pick 3-4 fields of your choice to make it easier on the user. But the crux of the matter is you need to do it. Any software that relies on user interaction cannot do without it – and so is our iPhone video chat.

To handle user management, we need a central server. To our great comfort, there are number of cloud solutions available again. For the purpose of this tutorial, I have chosen because it boasts of 100k+ apps live, and is backed by Facebook. It claims easiest of the APIs, and those claims, as I have experienced, are right. What’s more, it’s cross platform, so if you plan to make Android or Windows mobile client for your video chat app, you are in safe hands.

The objectives of this tutorial are to show:

  • How to enable users see each other (Your favorite messenger’s who’s online sort)
  • How to make them talk with each other using Opentok video streaming feature in your next great iphone video chat app

Tokbox provides a Broadcast tutorial which contains some of what we need for a fully featured chap app. The main difference is that we’re creating a two-way chat instead of a one-to-many broadcast system. I’ll also try to simplify the process so that even novice developers should be able to finish it without much trouble.

Setup ( and for your iPhone video chat app – LiveSessions:

My showcase app – Livesessions – requires some configuration on both and profiles – the server side. needs your app, and so does, although it names it a Project.

I assume you know enough to configure an app on In addition to it, you also need 2 data tables – ActiveUsers and ActiveSessions, though there is no need to pre-populate them at any point. Here is a snap of what their column lists will look like:


  • userID – String
  • userLocation – Geopoint
  • userTitle – String


  • callerID – String
  • callerTitle – String
  • receiverID – String
  • sessionID – String
  • publisherToken – String
  • subscriberToken – String
  • isVideo – Boolean
  • isAudio – Boolean

Similarly, on, once you login, go to dashboard and create new project, it will automatically create an API key and API secret. Note that these are your credential as a Tokbox developer, not a chat user. API key is more like your user ID and API secret is a password.

The resulting Tokbox dashboard screen will look like this (the real API key and text are hidden):

iPhone video chat

There is one, crucial piece left to be done to finish the server side. As we discussed earlier, we need to connect our streaming application server ( with authentication server ( Unless this is done, streaming server has no way to know which user is calling whom because all it knows about is session ID. Our iPhone video chat user, on the other hand, only knows about his own user credentials supplied to him by

As it is apparent, it is’s job to connect the two. That is:

  • To intercept logged in user’s request to chat (the caller).
  • To convert it into Tokbox session ID, get the session ID and other necessary information (the token) from Tokbox.
  • To send the caller and receiver ( users) the sessionID.
  • Since both users now have a session ID and a token which is received from, they can seamlessly communicate via Tokbox streaming server.

To accomplish above, must obtain sessionID, publisherToken and subscriberToken from tokbox, and that is where Parse cloud code comes into picture. In Parse Cloud code section, you must upload some code so that the resulting screen looks like this:

The process of uploading (oops, deploying) cloud code on is described in this source tutorial (Setting Up section) and here, and it is far better than I could explain here. So let’s skip it to maintain the scope. However for simplicity’s sake, I have included it step by step in readme.txt that comes within the code.

I would still take a few moments to explain what this code does, and why. The iPhone app user initiates a call to another user. No, he does not make a phone call. Remember, it’s LiveSession app’s job to handle the entire call, just like Skype or Yahoo messenger does. What our iPhone app needs to do under the hood is fairly simple task: it is saving a row to ActiveSessions Parse table we just created. There, it stores caller user ID (callerID) and receiver user ID (receiverID) among other things.

Now what this cloud code does is something quite magical, yet simple. It intercepts the Save operation in its beforeSave cloud trigger – nicely elaborated here. From within beforesave, Opentok javascript API takes over. Opentok supplied function createSession generates a session ID. Another function, Opentok.generateToken, creates a publisher token or subscriber token, depending on the role argument passed, which decides whether you want to publish your own video feed (Opentok.ROLE.PUBLISHER) or see other user’s video feed (Opentok.ROLE.SUBSCRIBER) using that session ID. (It is unclear from my experience if there is any difference between the two. For the scope of this discussion let us generate both as we need two-way video feeds anyway.)

Since we must remember we are within beforeSave trigger, we already have the handle to the object being saved – ActiveSessions. By simply setting its respective members – we can save three distinct items to our database: sessionID, publisherToken and subscriberToken – all three columns in ActiveSession table.

Well – that’s for that. What? You are done with the back end of your first iPhone video chat app! Congratulations!

But how? All we required for two user’s to connect via streaming server is a user id (session id) and a password (token) – and we have both. Now all we have to do is – avail them to iOS client via Not that it’s quite easy as 1-2-3, but the mammoth has bitten the dust already.

Serve yourself a cup of hot coffee as you wait to see one of your friends on your iPhone video app screen! Well, not quite quickly, but before you jump in, you can do them some favor: read this disclaimer if it can help any of your Android friends:

iOS client – the other part of the deal:

Now that the back end is accomplished, let’s focus on how iOS client – our own LiveSession iPhone app – keeps its part of the deal. The major tasks we aim to cover are:

1) Initiate iPhone video chat call – by saving an ActiveSession row (we already described the server part of it above as part of cloud code)

2) Handle Incoming Call – check database for an incoming video call – described down the line.

Let’s tackle each of them – one by one. But first and foremost, let’s setup the basic iOS project and go over what’s all needed.

iPhone Video Chat Initial Project Setup:

Open XCode, setup a single View application with default options. Name it LiveSessions. In storyboards, set up 2 scenes: One for users list – named LSViewController (derived from UIViewController), and another for hosting video chat view, LSStreamingViewController (again, subclass of UIViewController).

Next, add a UITableView object to LSViewController scene through storyboard. This table view must maintain a list of users who log into LiveSession app any time. LSViewController will handle all the chores related to UITableView, nothing unusual. Do not forget to implement UITableViewDelegate and UITableViewDatasource protocols in LSViewController so as to handle table view related stuff.

In addition to the above, we also need a helper class called ParseHelper which wraps our calls to Parse. All of its members and functions would be static.

To use Parse and Opentok framework, we need to link them, as well as some of the required frameworks used by both of them.

Parse framework can be obtained from here.

Opentok SDK can be obtained from here. This link also explains at length what all you need to do in order to link Opentok framework successfully.

Next, you should add some libraries to LiveSessions by selecting it, going to Build Phases->Link Binary section. After adding number of frameworks, this section should look like this:

At the end of linking everything, your Project tree should look like this:

(Notice the Opentok.bundle thing that come as part of Opentok sdk. Also see three other libraries that go below it in order to link everything together).

Before we proceed, let’s have one look at how beautiful (!) our storyboard looks:


Step 1 – Initiate Video Call: acts as a mediator between caller, Opentok streaming engine and receiver. The first and foremost requirement is to generate sessionID, publisherToken and subscriberToken, so that both clients can seamlessly connect via Opentok once session is established. We already know the cloud code does that. But how will LiveSessions app invoke the cloud code?

The following code not only stores an ActiveSessions object to Parse, but also invokes cloud code (beforeSave trigger) we discussed above that generates sessionID, publisherToken and subscriberToken – and they are eventually stored into ActiveSessions table itself.

  1. //ParseHelper.m
  2. //will initiate the call by saving session
  3. //if there is a session already existing, do not save,
  4. //just pop an alert
  5. +(void)saveSessionToParse:(NSDictionary *)inputDict
  6. {    
  7.     NSString * receiverID = [inputDict objectForKey:@"receiverID"];
  9.     //check if the recipient is either the caller or receiver in one of the activesessions.
  10.     NSPredicate *predicate = [NSPredicate predicateWithFormat:
  11.                               @"receiverID = '%@' OR callerID = %@", receiverID, receiverID];
  12.     PFQuery *query = [PFQuery queryWithClassName:@"ActiveSessions" predicate:predicate];
  14.     [query getFirstObjectInBackgroundWithBlock:^
  15.     (PFObject *object, NSError *error)
  16.     {
  17.         if (!object)
  18.         {
  19.             NSLog(@"No session with receiverID exists.");
  20.             [self storeToParse:inputDict];
  21.         }
  22.         else
  23.         {
  24.            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kReceiverBusyNotification object:nil]];
  25.            return;
  26.         }
  27.     }];
  28. }
  30. +(void) storeToParse:(NSDictionary *)inputDict
  31. {
  32.     __block PFObject *activeSession = [PFObject objectWithClassName:@"ActiveSessions"];
  33.     NSString * callerID = [inputDict objectForKey:@"callerID"];
  34.     if (callerID)
  35.     {
  36.         [activeSession setObject:callerID forKey:@"callerID"];
  37.     }
  38.     bool bAudio = [[inputDict objectForKey:@"isAudio"]boolValue];
  39.     [activeSession setObject:[NSNumber numberWithBool:bAudio] forKey:@"isAudio"];
  41.     bool bVideo = [[inputDict objectForKey:@"isVideo"]boolValue];
  42.     [activeSession setObject:[NSNumber numberWithBool:bVideo] forKey:@"isVideo"];
  44.     NSString * receiverID = [inputDict objectForKey:@"receiverID"];
  45.     if (receiverID)
  46.     {
  47.         [activeSession setObject:receiverID forKey:@"receiverID"];
  48.     }
  50.     //callerTitle
  51.     NSString * callerTitle = [inputDict objectForKey:@"callerTitle"];
  52.     if (receiverID)
  53.     {
  54.         [activeSession setObject:callerTitle forKey:@"callerTitle"];
  55.     }
  57.     [activeSession saveInBackgroundWithBlock:^(BOOL succeeded, NSError* error)
  58.     {
  59.         if (!error)
  60.         {
  61.              NSLog(@"sessionID: %@, publisherToken: %@ , subscriberToken: %@", activeSession[@"sessionID"],activeSession[@"publisherToken"],
  62.                    activeSession[@"subscriberToken"]);
  64.              LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  65.              appDelegate.sessionID = activeSession[@"sessionID"];
  66.              appDelegate.subscriberToken = activeSession[@"subscriberToken"];
  67.              appDelegate.publisherToken = activeSession[@"publisherToken"];
  68.              appDelegate.callerTitle = activeSession[@"callerTitle"];
  69.              [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kSessionSavedNotification object:nil]];
  70.          }
  71.          else
  72.          {
  73.              NSLog(@"savesession error!!! %@", [error localizedDescription]);
  74.              NSString * msg = [NSString stringWithFormat:@"Failed to save outgoing call session. Please try again.  %@", [error localizedDescription]];
  75.              [self showAlert:msg];
  76.          }        
  77.      }];
  78. }

At the end of executing the above code, we should have a sessionID, publisherToken as well as subscriberToken in our ActiveSessions table. Alright, but who will execute it? Lot of stuff still remain unanswered – for example, from where does all the argument values (receiverID, callerID) come from? We deliberately missed that part, because establishing the session was most important. The callerID, receiverID parameters that we used above are actually just the user IDs generated by PFUser object. You can have your own way of registering and authenticating a user. In LiveSessions, we just store each user within ActiveUsers table, and only using a user title of his / her own choice. No emails, passwords or verification. And here is code that is responsible for it:

  1. //ParseHelper.m
  2. +(void) showUserTitlePrompt
  3. {
  4.     UIAlertView *userNameAlert = [[UIAlertView alloc] initWithTitle:@"LiveSessions" message:@"Enter your name:" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
  5.     userNameAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
  6.     userNameAlert.tag = kUIAlertViewTagUserName;
  7.     [userNameAlert show];
  8. }
  10. +(void) anonymousLogin
  11. {
  12.     loggedInUser = [PFUser currentUser];
  13.     if (loggedInUser)
  14.     {
  15.         [self showUserTitlePrompt];      
  16.         return;
  17.     }
  19.     [PFAnonymousUtils logInWithBlock:^(PFUser *user, NSError *error)
  20.      {
  21.          if (error)
  22.          {
  23.              NSLog(@"Anonymous login failed.%@", [error localizedDescription]);
  24.              NSString * msg = [NSString stringWithFormat:@"Failed to login anonymously. Please try again.  %@", [error localizedDescription]];
  25.              [self showAlert:msg];
  26.          }
  27.          else
  28.          {            
  29.              loggedInUser = [PFUser user];
  30.              loggedInUser = user;
  31.              [self showUserTitlePrompt];
  32.          }
  33.      }];
  34. }

What this does is simple: when the app launches, check for the locally stored Parse user ([PFUser currentUser]), and if one does not exist, perform anonymous login, which will create a PFUser object on Users table. What is important to us is loggedInUser static object that we use to store currently logged on user. At the end of successful login, showUserTitlePrompt function prompts the user to enter a title of his / her choice.

Fine, but what happens when user enters it? Well, significant number things. For a start, here is how LiveSessions handles it:

  1. //ParseHelper.m
  2. + (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  3. {
  4.     if (kUIAlertViewTagUserName == alertView.tag)
  5.     {
  6.         //lets differe saving title till we have the location.
  7.         //saveuserwithlocationtoparse will handle it.
  8.         LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  9.         appDelegate.userTitle = [[alertView textFieldAtIndex:0].text copy];
  10.         appDelegate.bFullyLoggedIn = YES;
  12.         //fire appdelegate timer
  13.         [appDelegate fireListeningTimer];
  14.         [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kLoggedInNotification object:nil]];
  15.     }
  16.     else if (kUIAlertViewTagIncomingCall == alertView.tag)
  17.     {
  18.         if (buttonIndex != [alertView cancelButtonIndex])   //accept the call
  19.         {
  20.             //accept the call
  21.             [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kIncomingCallNotification object:nil]];
  22.         }
  23.         else
  24.         {
  25.             //user did not accept call, restart timer          
  26.             //start polling for new call.
  27.             [self setPollingTimer:YES];
  28.         }
  29.     }
  30. }

Notice the part under tag kUIAlertViewTagUserName. This code tells LiveSessions that user is now fully logged in, along with an identification (title) of his / her choice. This title will be eventually stored into ActiveUsers table as userTitle, but with one more thing: user’s current location. Yes, LiveSessions is a location-aware app. And to obtain user’s location, ParseHelper.m posts a kLoggedInNotification notification to LSViewController. LSViewController has CLLocationManager code inside it which will track user’s current location. At the end, once we have everything, the entire user (his title, user ID and location) are saved into ActiveUsers table.

Here is what goes inside LSViewController to obtain user’s current location, and call to Parse wrapper for storing it to ActiveUsers table:

  1. //LSViewController.m
  2. //Called in response of kLoggedInNotification
  3. - (void) didLogin
  4. {
  5.    [self startUpdate];
  6. }
  8. #pragma location methods
  9. //this will invoke locationManager to track user's current location
  10. - (void)startUpdate
  11. {
  12.     if (locationManager)
  13.     {
  14.         [locationManager stopUpdatingLocation];
  15.     }
  16.     else
  17.     {
  18.         locationManager = [[CLLocationManager alloc] init];
  19.         [locationManager setDelegate:self];
  20.         [locationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
  21.         [locationManager setDistanceFilter:30.0];
  22.     }
  24.     [locationManager startUpdatingLocation];
  25. }
  27. //stop tracking location
  28. - (void)stopUpdate
  29. {
  30.     if (locationManager)
  31.     {
  32.         [locationManager stopUpdatingLocation];
  33.     }
  34. }
  36. //this will store finalized user location.
  37. //once done, it will save it in ActiveUsers row and then fetch nearer users to show in table.
  38. - (void)locationManager:(CLLocationManager *)manager
  39.     didUpdateToLocation:(CLLocation *)newLocation
  40.            fromLocation:(CLLocation *)oldLocation
  41. {  
  43.     CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
  44.     //discard if inaccurate, or if user hasn't moved much.
  45.     if (meters != -1 && meters < 50.0)
  46.         return;
  48.     NSLog(@"## Latitude  : %f", newLocation.coordinate.latitude);
  49.     NSLog(@"## Longitude : %f", newLocation.coordinate.longitude);
  51.     appDelegate.currentLocation = newLocation;
  53.     //pause the updates, until didUserLocSaved is called
  54.     //via kUserLocSavedNotification notification, to avoid multiple saves.
  55.     [self stopUpdate];
  57.     PFUser * thisUser = [ParseHelper loggedInUser] ;
  59.     [ParseHelper saveUserWithLocationToParse:thisUser :[PFGeoPoint geoPointWithLocation:appDelegate.currentLocation]];
  60.     [self fireNearUsersQuery:RANGE_IN_MILES :appDelegate.currentLocation.coordinate :YES];
  61. }

The first unknown in above code so far is call to fireNearUsersQuery function,which serves front end. We will come to it later. The other unknown is saveUserWithLocationToParse function, which will fill the gaps left so far to complete the back end. It belongs to ParseHelper.m, and here it goes – there is nothing unusual about storing it, and it acts as our own little user repository. The generated user’s object ID is stored for later use inside activeUserObjectID.

  1. //ParseHelper.m
  2. + (void) saveUserWithLocationToParse:(PFUser*) user :(PFGeoPoint *) geopoint
  3. {
  4.     __block PFObject *activeUser;
  6.     PFQuery *query = [PFQuery queryWithClassName:@"ActiveUsers"];
  7.     [query whereKey:@"userID" equalTo:user.objectId];
  8.     [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
  9.     {
  10.         if (!error)
  11.         {
  12.             // if user is active user already, just update the entry
  13.             // otherwise create it.
  14.             if (objects.count == 0)
  15.             {
  16.                 activeUser = [PFObject objectWithClassName:@"ActiveUsers"];
  17.             }
  18.             else
  19.             {                
  20.                 activeUser = (PFObject *)[objects objectAtIndex:0];
  21.             }
  22.             LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  23.             [activeUser setObject:user.objectId forKey:@"userID"];
  24.             [activeUser setObject:geopoint forKey:@"userLocation"];
  25.             [activeUser setObject:appDelegate.userTitle forKey:@"userTitle"];
  26.             [activeUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
  27.             {
  28.                 if (error)
  29.                 {
  30.                     NSString * errordesc = [NSString stringWithFormat:@"Save to ActiveUsers failed.%@", [error localizedDescription]];
  31.                     [self showAlert:errordesc];
  32.                     NSLog(@"%@", errordesc);
  33.                 }
  34.                 else
  35.                 {
  36.                     NSLog(@"Save to ActiveUsers succeeded.");
  37.                     activeUserObjectID = activeUser.objectId;
  39.                     NSLog(@"%@", activeUserObjectID);
  40.                 }
  41.                 [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kUserLocSavedNotification object:nil]];
  42.             }];
  43.         }
  44.         else
  45.         {
  46.             NSString * msg = [NSString stringWithFormat:@"Failed to save updated location. Please try again.  %@", [error localizedDescription]];
  47.             [self showAlert:msg];
  48.         }
  49.     }];
  50. }

The code so far ensured a user is saved inside ActiveUsers table. We also saw how he / she can initiate a video call to another user, by creating an ActiveSessions object. But whom does the user chat with?

We must also present a list of users to logged on user to chat with – equivalent of Yahoo/Skype friend’s list. Sending friend requests through email or any other means would be quite an overkill for our tutorial’s scope. To keep things minimal, we don’t even ask our users to enter their email ID for registration.

Instead, we have chosen a unique way to test out video chat feature: show list of users who are geographically within specified radii – say 200 miles. already has PFGeopoint related query mechanism which makes our task easier.

The other unknown in code above, fireNearUsersQuery goes as below, and it fills up the datasource for the LSViewController table view – an NSMutableArray made of dictionaries filled with user’s titles:

  1. //LSViewController.m
  2. //this method polls for new users that gets added / removed from surrounding region.
  3. //distanceinMiles - range in Miles
  4. //bRefreshUI - whether to refresh table UI
  5. //argCoord - location around which to execute the search.
  6. -(void) fireNearUsersQuery : (CLLocationDistance) distanceinMiles :(CLLocationCoordinate2D)argCoord :(bool)bRefreshUI
  7. {
  8.     CGFloat miles = distanceinMiles;
  9.     NSLog(@"fireNearUsersQuery %f",miles);
  11.     PFQuery *query = [PFQuery queryWithClassName:@"ActiveUsers"];
  12.     [query setLimit:1000];
  13.     [query whereKey:@"userLocation"
  14.        nearGeoPoint:
  15.      [PFGeoPoint geoPointWithLatitude:argCoord.latitude longitude:argCoord.longitude] withinMiles:miles];    
  17.     //delete all existing rows,first from front end, then from data source.
  18.     [m_userArray removeAllObjects];
  19.     [m_userTableView reloadData];    
  21.     [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
  22.     {
  23.         if (!error)
  24.         {
  25.             for (PFObject *object in objects)
  26.             {
  27.                 //if for this user, skip it.
  28.                 NSString *userID = [object valueForKey:@"userID"];
  29.                 NSString *currentuser = [ParseHelper loggedInUser].objectId;
  30.                 NSLog(@"%@",userID);
  31.                 NSLog(@"%@",currentuser);
  33.                 if ([userID isEqualToString:currentuser])
  34.                 {
  35.                     NSLog(@"skipping - current user");
  36.                     continue;
  37.                 }
  39.                 NSString *userTitle = [object valueForKey:@"userTitle"];
  41.                 NSMutableDictionary * dict = [NSMutableDictionary dictionary];
  42.                 [dict setObject:userID forKey:@"userID"];
  43.                 [dict setObject:userTitle forKey:@"userTitle"];
  45.                 // TODO: if reverse-geocoder is added, userLocation can be converted to
  46.                 // meaningful placemark info and user's address can be shown in table view.
  47.                 // [dict setObject:userTitle forKey:@"userLocation"];
  48.                 [m_userArray addObject:dict];
  49.             }
  51.             //when done, refresh the table view
  52.             if (bRefreshUI)
  53.             {
  54.                 [m_userTableView reloadData];
  55.             }
  56.         }
  57.         else
  58.         {
  59.             NSLog(@"%@",[error description]);
  60.         }
  61.     }];
  62. }

The result of fireNearUsersQuery call will be somewhat like below, where 3 nearby users (<200 miles radii) are visible for chat:


Inside LSViewController, the m_userTableView gets populated from m_userArray. Each row in the table view has a green Call button. When you tap that button, call is initiated for that user as the receiver ID. What call? The code we just covered to store the session: saveSessionToParse. Who calls it? Well, now it’s time the video chat scene (LSStreamingViewController) takes charge.

Before proceeding, take a look at this activity flow – the big picture. You will come back to it quite often as you read on:


Upon tapping of the green phone call button, a segue is performed to transition to LSStreamingViewController. Inside LSStreamingViewController, [ParsHelper saveSessionToParse] is called. Here is that part:

  1. //LSViewController.m
  2. - (void) startVideoChat:(id) sender
  3. {
  4.     UIButton * button = (UIButton *)sender;
  6.     if (button.tag < 0) //out of bounds
  7.     {
  8.         [ParseHelper showAlert:@"User is no longer online."];
  9.         return;
  10.     }
  12.     NSMutableDictionary * dict = [m_userArray objectAtIndex:button.tag];
  13.     NSString * receiverID = [dict objectForKey:@"userID"];
  14.     m_receiverID = [receiverID copy];
  15.     [self goToStreamingVC];
  16. }
  18. - (void) goToStreamingVC
  19. {
  20.     //[self presentModalViewController:streamingVC animated:YES];
  21.     //
  22.     [self performSegueWithIdentifier:@"StreamingSegue" sender:self];
  23. }
  25. -(void) prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
  26. {
  27.     if ([segue.identifier isEqualToString:@"StreamingSegue"])
  28.     {    
  29.         UINavigationController * navcontroller =  (UINavigationController *) segue.destinationViewController;        
  30.         LSStreamingViewController * streamingVC =  (LSStreamingViewController *)navcontroller.topViewController;        
  31.         streamingVC.callReceiverID = [m_receiverID copy];    
  32.         if (bAudioOnly)
  33.         {
  34.             streamingVC.bAudio = YES;
  35.             streamingVC.bVideo = NO;
  36.         }
  37.         else
  38.         {
  39.             streamingVC.bAudio = YES;
  40.             streamingVC.bVideo = YES;
  41.         }
  42.     }
  43. }

Once inside LSStreamingViewController:

  1. //LSStreamingViewController.m
  2. - (void) viewDidAppear:(BOOL)animated
  3. {
  4.     if (![self.callReceiverID isEqualToString:@""])
  5.     {
  6.         m_mode = streamingModeOutgoing; //generate session
  7.         [self initOutGoingCall];
  8.         //connect, publish/subscriber -> will be taken care by
  9.         //sessionSaved observer handler.
  10.     }
  11.     else
  12.     {
  13.         m_mode = streamingModeIncoming; //connect, publish, subscribe
  14.         m_connectionAttempts = 1;
  15.         [self connectWithPublisherToken];
  16.     }
  17. }
  19. - (void) initOutGoingCall
  20. {
  21.     NSMutableDictionary * inputDict = [NSMutableDictionary dictionary];
  22.     [inputDict setObject:[ParseHelper loggedInUser].objectId forKey:@"callerID"];
  23.     [inputDict setObject:appDelegate.userTitle forKey:@"callerTitle"];
  24.     [inputDict setObject:self.callReceiverID forKey:@"receiverID"];
  25.     [inputDict setObject:[NSNumber numberWithBool:self.bAudio] forKey:@"isAudio"];
  26.     [inputDict setObject:[NSNumber numberWithBool:self.bVideo] forKey:@"isVideo"];
  27.     m_connectionAttempts = 1;
  28.     [ParseHelper saveSessionToParse:inputDict];
  29. }

As a matter of its duty, LSStreamingViewController handles both outgoing and incoming calls. To differentiate the two, it uses receiver ID (self.callreceiverID): For outgoing calls, it has a value supplied from LSViewController (see the segue transition code). For incoming calls, there is no need for it so it is null or empty.

As soon as saveSessionToParse saves ActiveSessions object to database, it notifies LSStreamingViewController so that sessionID, publisherToken and subscriberToken values from Opentok (that became available to app’s delegate) can be usable to LSStreamingViewController. This notification (kSessionSavedNotification) is handled by sessionSaved like this:

  1. //LSStreamingViewController.m
  2. - (void) sessionSaved
  3. {
  4.     [self connectWithSubscriberToken];
  5. }

In forthcoming section we will see how the above call makes video chat fully seamless between two users, without Parse intervention.

Huh..the mammoth has been laid to rest, but there is still life in it. We already covered session generation part. But how does the other user know about it? And when exactly Opentok takes the charge to start the exciting video?

Step 2 – Handle Incoming Call:

Handling of an incoming call is tricky bit. Let’s list out the bare minimum necessities:

  • You need to poll the database for a session destined to you (logged on user) – that is – search for an ActiveSessions record where current user is listed as receiver.
  • You need to ensure that database is up-to-date once the call has been established – that is, remove the session row once sessionID and tokens have been read up into iPhone app
  • You also need to signal interruptions while a session is ON – that is, inform the caller gracefully that the receiver is busy on another call. For simplicity’s sake, we aren’t handling multi-user calls (conference) right now, although it can be handled quite easily.

Recall that in alertView:(UIAlertView *)alertView clickedButtonAtIndex, we saw a call to [appDelegate fireListeningTimer],and now it is time to expand it, because it accomplishes our first task of the three listed above: It fires a timer that continually polls ActiveSessions table for calls destined to current user.

  1. //LSAppDelegate.m
  2. //this method will be called once logged in. It will poll parse ActiveSessions object
  3. //for incoming calls.
  4. -(void) fireListeningTimer
  5. {
  6.     if (self.appTimer && [self.appTimer isValid])
  7.         return;
  9.     self.appTimer = [NSTimer scheduledTimerWithTimeInterval:8.0
  10.                                                      target:self
  11.                                                    selector:@selector(onTick:)
  12.                                                    userInfo:nil
  13.                                                     repeats:YES];
  14.     [ParseHelper setPollingTimer:YES];  
  15.     NSLog(@"fired timer");
  16. }
  18. -(void)onTick:(NSTimer *)timer
  19. {
  20.     NSLog(@"OnTick");
  21.     [ParseHelper pollParseForActiveSessions];  
  22. }

As it is named, [ParseHelper pollParseForActiveSessions] will poll ActiveSessions table for sessions calling out to this user – that is, rows which have receiverID = currently logged on user’s object ID.

  1. //ParseHelper.m
  2. //poll parse ActiveSessions object for incoming calls.
  3.  +(void) pollParseForActiveSessions
  4.  {
  5.      __block PFObject *activeSession;
  7.      if (!bPollingTimerOn)
  8.          return;
  10.      PFQuery *query = [PFQuery queryWithClassName:@"ActiveSessions"];
  12.      NSString* currentUserID = [self loggedInUser].objectId;
  13.      [query whereKey:@"receiverID" equalTo:currentUserID];  
  15.      [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
  16.       {
  17.           if (!error)
  18.           {
  19.               // if user is active user already, just update the entry
  20.               // otherwise create it.
  21.               LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  23.               if (objects.count == 0)
  24.               {
  26.               }
  27.               else
  28.               {
  29.                   activeSession = (PFObject *)[objects objectAtIndex:0];                
  30.                   appDelegate.sessionID = activeSession[@"sessionID"];
  31.                   appDelegate.subscriberToken = activeSession[@"subscriberToken"];
  32.                   appDelegate.publisherToken = activeSession[@"publisherToken"];
  33.                   appDelegate.callerTitle = activeSession[@"callerTitle"];
  34.                  // future use:
  35.                   //appDelegate.bAudioCallOnly = !([activeSession[@"isVideo"] boolValue]);
  37.                   //done with backend object, remove it.
  38.                   [self setPollingTimer:NO];
  39.                   [self deleteActiveSession];
  41.                   NSString *msg = [NSString stringWithFormat:@"Incoming Call from %@, Accept?", appDelegate.callerTitle];                  
  42.                   UIAlertView *incomingCallAlert = [[UIAlertView alloc] initWithTitle:@"LiveSessions" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];                
  43.                   incomingCallAlert.tag = kUIAlertViewTagIncomingCall;
  44.                   [incomingCallAlert show];                
  45.               }
  46.           }
  47.           else
  48.           {
  49.               NSString * msg = [NSString stringWithFormat:@"Failed to retrieve active session for incoming call. Please try again. %@", [error localizedDescription]];
  50.               [self showAlert:msg];
  51.           }
  52.      }];
  53. }

The method is quite self-explanatory – whenever it finds an ActiveSessions object, it just copies all the fields it needs – sessionID, publisherToken, and subscriberToken into app delegate’s properties. Once done, it deletes it from backend using [self deleteActiveSession] call. [self setPollingTimer:NO] is to keep things in sync: it ensures that timer doesn’t fire up another polling query through pollParseForActiveSessions after an object has been found and deletion is in progress using [self deleteActiveSession].

Once the ActiveSession values are copied to App’s delegate, more important stuff is waiting: user needs to be notified of an incoming call. incomingCallAlert performs this task, and here is the result:


What’s more important is incomingCallAlert's delegate, which we already visited in Step 1 – let’s go over it again:

  1. //ParseHelper.m
  2. + (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  3. {
  4.     if (kUIAlertViewTagUserName == alertView.tag)
  5.     {
  6.         //lets differ saving title till we have the location.
  7.         //saveuserwithlocationtoparse will handle it.
  8.         LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  9.         appDelegate.userTitle = [[alertView textFieldAtIndex:0].text copy];
  10.         appDelegate.bFullyLoggedIn = YES;
  12.         //fire appdelegate timer
  13.         [appDelegate fireListeningTimer];
  14.         [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kLoggedInNotification object:nil]];
  15.     }
  16.     else if (kUIAlertViewTagIncomingCall == alertView.tag)
  17.     {
  18.         if (buttonIndex != [alertView cancelButtonIndex])   //accept the call
  19.         {
  20.             //accept the call
  21.             [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:kIncomingCallNotification object:nil]];
  22.         }
  23.         else
  24.         { 
  25.             //user did not accept call, restart timer
  26.             //start polling for new call.
  27.             [self setPollingTimer:YES];
  28.         }
  29.     }
  30. }

If user had not accepted the call, the polling timer flag is set and app starts to look for new incoming call session. If user rather decides to accept the call, kIncomingCallNotification is posted, and it is responsible for notifying LSViewController that a call has arrived. In fact, any view controller within your chat app should be able to receive this notification, so that you can handle the call irrespective of where you are in the app. Such notifications can be handled by having a UIViewController subclass from which all your view controllers can inherit. For simplicity, Livesessions only has one view controller that handles incoming call, and here is how:

  1. //if and when a call arrives-
  2. (void) didCallArrive
  3. {    
  4.      //pass blank because call has arrived, no need for receiverID.
  5.      m_receiverID = @"";
  6.      [self goToStreamingVC];
  7. }

didCallArrive fires in response to kIncomingCallNotification, and all it does it empty the m_receiverID to indicate that call is destined to self – an incoming call. This, as we already saw in prepareForSegue – is enough to signal LSStreamingViewController that call is supposed to be handled as incoming call – so no new ActiveSessions object need to be stored. All that is left is to utilize the sessionID and token values to connect to Tokbox streaming server.

So far, we discussed both cases – in both we obtained sessionID, publisherToken and subscriberToken into our app’s delegate. We finally passed the control over to LSStreamingViewController. In case of an outgoing call, [LSStreamingViewController sessionSaved] function calls [LSStreamingViewController connectWithSubscriberToken]. In case of incoming call, as we already saw in [LSStreamingViewController viewDidAppear], a call is made to [LSStreamingViewController connectWithPublisherToken].

  1. //LSStreamingViewController.m
  2. - (void) connectWithPublisherToken
  3. {
  4.     NSLog(@"connectWithPublisherToken");
  5.     [self doConnect:appDelegate.publisherToken :appDelegate.sessionID];
  6. }
  8. - (void) connectWithSubscriberToken
  9. {
  10.     NSLog(@"connectWithSubscriberToken");    
  11.     [self doConnect:appDelegate.subscriberToken :appDelegate.sessionID];
  12. }
  14. - (void)doConnect : (NSString *) token :(NSString *) sessionID
  15. {
  16.     _session = [[OTSession alloc] initWithSessionId:sessionID
  17.                                            delegate:self];
  18.     [_session addObserver:self forKeyPath:@"connectionCount"
  19.                   options:NSKeyValueObservingOptionNew
  20.                   context:nil];
  21.     [_session connectWithApiKey:kApiKey token:token];
  22. }

The only difference between two of them is the token they use – and Opentok isn’t quite clear about what changes if you use one token instead of the other (publisher token or subscriber token – as you remember it is generated from cloud code in beforeSave trigger). Irrespective of which one you use to connect to a session, it allows you to publish your stream (your camera feed) as well as subscribe to other user’s stream.

Once [_session connectWithApiKey] call is made, Opentok takes over. All you need to remember is that your streaming view controller (LSStreamingViewController) must implement these protocols: OTSessionDelegate, OTSubscriberDelegate, OTPublisherDelegate. See the activity flow diagram up again – there, iOS app initiated actions are listed in yellow, and delegates are marked in green. These delegate functions are part of these three protocols that LSStreamingViewController must implement. As they are called by Opentok along the flow, you need to take various actions to make that enticing video available to your user.

Now it no longer matters whether you are a caller or a receiver as far as you implement necessary delegate methods from Opentok. The Broadcast tutorial from Opentok has all implementation details, and I have followed it bit by bit, apart from my own UI modifications. For example, if you choose to view your own stream as soon as session gets connected, following code accomplishes it:

  1. //LSStreamingViewController.m
  2. - (void)sessionDidConnect:(OTSession*)session
  3. {
  4.     NSLog(@"sessionDidConnect: %@", session.sessionId);
  5.     NSLog(@"- connectionId: %@", session.connection.connectionId);
  6.     NSLog(@"- creationTime: %@", session.connection.creationTime);
  7.     [self.disconnectButton setHidden:NO];
  8.     [self.view bringSubviewToFront:self.disconnectButton];
  10.     self._statusLabel.text = @"Connected, waiting for stream...";  
  11.     [self.view bringSubviewToFront:self._statusLabel];
  13.     [self doPublish];
  14. }
  16. - (void)doPublish
  17. {
  18.     _publisher = [[OTPublisher alloc] initWithDelegate:self];
  19.     _publisher.publishAudio = self.bAudio;
  20.     _publisher.publishVideo = self.bVideo;
  21.     [_session publish:_publisher];
  23.     //symmetry is beauty.
  24.     float x = 5.0;
  25.     float y = 5.0;
  26.     float publisherWidth = 120.0;
  27.     float publisherHeight = 120.0;
  29.     [_publisher.view setFrame:CGRectMake(x,y,publisherWidth,publisherHeight)];
  30.     [self.view addSubview:_publisher.view];
  31.     [self.view bringSubviewToFront:self.disconnectButton];
  32.     [self.view bringSubviewToFront:self._statusLabel];
  34.     NSLog(@"%f-%f-%f-%f", _publisher.view.frame.origin.x, _publisher.view.frame.origin.y, _publisher.view.frame.size.width, _publisher.view.frame.size.height);
  36.     _publisher.view.layer.cornerRadius = 10.0;
  37.     _publisher.view.layer.masksToBounds = YES;
  38.     _publisher.view.layer.borderWidth = 5.0;
  39.     _publisher.view.layer.borderColor = [UIColor yellowColor].CGColor;
  40. }

In the code above, [_session publish] call prompts the user to allow his / her own camera feed, and as soon as he / she allows it, LiveSessions start publishing the camera feed to Opentok streaming server. A crucial piece to remember here is the call to following:

  1. _publisher.view setFrame

SDK is designed such that without this, you never get to see your own feed. And no, any indirect method (e.g. addSubView to a container view) to set the frame doesn’t work. At the same time you can decorate your publisher view. For example, we have changed features like border color and corner radius.

Seeing the feed of the other user in the same session is somewhat that doesn’t fall into any order. All you need to do is implement necessary delegates so that as soon as you start receiving that feed, you get an opportunity to configure it fully – like this:

  1. //LSStreamingViewController.m
  2. - (void)subscriberDidConnectToStream:(OTSubscriber*)subscriber
  3. {
  4.     NSLog(@"subscriberDidConnectToStream (%@)",;
  6.     float subscriberWidth = [[UIScreen mainScreen] bounds].size.width;
  7.     float subscriberHeight = [[UIScreen mainScreen] bounds].size.height - self.navigationController.navigationBar.frame.size.height;
  9.     NSLog(@"screenheight %f", [[UIScreen mainScreen] bounds].size.height);
  10.     NSLog(@"navheight %f", self.navigationController.navigationBar.frame.size.height);
  12.     //fill up entire screen except navbar.
  13.     [subscriber.view setFrame:CGRectMake(0, 0, subscriberWidth, subscriberHeight)];
  15.     [self.view addSubview:subscriber.view];
  16.     self.disconnectButton.hidden = NO;
  18.     if (_publisher)
  19.     {
  20.         [self.view bringSubviewToFront:_publisher.view];
  21.         [self.view bringSubviewToFront:self.disconnectButton];
  22.         [self.view bringSubviewToFront:self._statusLabel];
  23.     }
  24.     subscriber.view.layer.cornerRadius = 10.0;
  25.     subscriber.view.layer.masksToBounds = YES;
  26.     subscriber.view.layer.borderWidth = 5.0;
  27.     subscriber.view.layer.borderColor = [UIColor lightGrayColor].CGColor;
  29.     self._statusLabel.text = @"Connected and streaming...";
  30.     [self.view bringSubviewToFront:self._statusLabel];
  31. }

subscriberDidConnectToStream delegate allows you to configure your own subscriber view. Again, setFrame statement is crucial and if you don’t include it or do it with wrong values, you may never get to see other user’s feed – something that can break your (and your friends’) heart! Again, you can do your own UI modifications such as reporting the current status (using _statusLabel) and decorating the subscriber view inside the same delegate.

There are plenty of other delegates that Opentok sdk provides that you can use to include various features to smarten your app.

For example, see how I chose to handle subscriber didFailWithError delegate:

  1. //LSStreamingViewController.m
  2. - (void)subscriber:(OTSubscriber *)subscriber didFailWithError:(OTError *)error
  3. {
  4.     NSLog(@"subscriber: %@ didFailWithError: ",;
  5.     NSLog(@"- code: %d", error.code);
  6.     NSLog(@"- description: %@", error.localizedDescription);
  7.     self._statusLabel.text = @"Error receiving video feed, disconnecting...";
  8.     [self.view bringSubviewToFront:self._statusLabel];
  9.     [self performSelector:@selector(doneStreaming:) withObject:nil afterDelay:5.0];
  10. }
  12. - (IBAction)doneStreaming:(id)sender
  13. {
  14.     [self disConnectAndGoBack];
  15. }
  17. - (void) disConnectAndGoBack
  18. {
  19.     [self doUnpublish];
  20.     [self doDisconnect];
  21.     self.disconnectButton.hidden = YES;
  22.     [ParseHelper deleteActiveSession];
  24.     //set the polling on.
  25.     [ParseHelper setPollingTimer:YES];
  26.     [self dismissModalViewControllerAnimated:YES];
  27. }

There is much more inside LSStreamingViewController that needs little or no explanation for someone who knows UIKit well. So we proudly declare that the mammoth may have stopped breathing -you can see it yourself:


By the way, who is that insane soul screaming in the publisher view? LiveSessions isn’t that smart – what it shows there is what your iPhone’s camera sees!

And yeah, if you didn’t notice, the sleeping beast is an elephant, not a mammoth. Mammoths existed only in ice age. So is this real?

Who knows, it’s just virtual. But so are nerds trolling in chat rooms.

All we need now is to discard the remnants to smoother the flow of our iPhone video chat – let’s do them in one go.

The Cleanup:

As a VOIP app, LiveSessions must either keep running in the background or do its part of cleanup as soon as it enters background. To preserve simplicity, I chose later. There are some rules laid by Apple to perform any task in background – be it trivial or not. Within LSAppDelegate.m, we cleanup our back end following those rules.

  1. - (void)applicationDidEnterBackground:(UIApplication *)application
  2. {    
  3.     backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
  5.         // Clean up any unfinished task business by marking where you        
  6.         // stopped or ending the task outright.        
  7.         [application endBackgroundTask:backgroundTask];        
  8.         backgroundTask = UIBackgroundTaskInvalid;        
  9.     }];
  11.     // Start the long-running task and return immediately.    
  12.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  13.     ^{
  14.         // Do the work associated with the task, preferably in chunks.
  15.         [ParseHelper deleteActiveSession];
  16.         [ParseHelper deleteActiveUser];
  17.         [application endBackgroundTask:backgroundTask];        
  18.         backgroundTask = UIBackgroundTaskInvalid;        
  19.     });    
  20. }

And we also wake up following those rules:

  1. - (void)applicationWillEnterForeground:(UIApplication *)application
  2. {
  3.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  4.     self.bFullyLoggedIn = NO;
  5.     [ParseHelper initData];
  6.     [ParseHelper anonymousLogin];    
  7. }

And here goes what we call in the above code:

  1. + (void) deleteActiveSession
  2. {
  3.     NSLog(@"deleteActiveSession");
  4.     LSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
  5.     NSString * activeSessionID = appDelegate.sessionID;
  7.     if (!activeSessionID || [activeSessionID isEqualToString:@""])
  8.         return;
  10.     PFQuery *query = [PFQuery queryWithClassName:@"ActiveSessions"];
  11.     [query whereKey:@"sessionID" equalTo:appDelegate.sessionID];
  13.     [query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error)
  14.     {
  15.         if (!object)
  16.         {
  17.             NSLog(@"No session exists.");    
  18.         }
  19.         else
  20.         {
  21.             // The find succeeded.
  22.             NSLog(@"Successfully retrieved the object.");
  23.             [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
  24.             {
  25.                 if (succeeded && !error)
  26.                 {
  27.                     NSLog(@"Session deleted from parse");                  
  28.                 }
  29.                 else
  30.                 {
  31.                     //[self showAlert:[error description]];
  32.                     NSLog(@"%@", [error description]);
  33.                 }
  34.             }];
  35.         }
  36.     }];
  37. }
  39. + (void) deleteActiveUser
  40. {
  41.     NSString * activeUserobjID = [self activeUserObjectID];
  42.     if (!activeUserobjID || [activeUserobjID isEqualToString:@""])
  43.         return;
  45.     PFQuery *query = [PFQuery queryWithClassName:@"ActiveUsers"];
  46.     [query whereKey:@"userID" equalTo:activeUserobjID];
  48.     [query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error)
  49.     {
  50.         if (!object)
  51.         {
  52.             NSLog(@"No such users exists.");
  53.         }
  54.         else
  55.         {
  56.             // The find succeeded.
  57.             NSLog(@"Successfully retrieved the ActiveUser.");
  58.             [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
  59.              {
  60.                  if (succeeded && !error)
  61.                  {
  62.                      NSLog(@"User deleted from parse");
  63.                      activeUserObjectID = nil;
  64.                  }
  65.                  else
  66.                  {
  67.                      //[self showAlert:[error description]];
  68.                       NSLog(@"%@", [error description]);
  69.                  }
  70.              }];
  71.         }
  72.     }];
  73. }
  75. +(void) initData
  76. {
  77.     if (!objectsUnderDeletionQueue)
  78.         objectsUnderDeletionQueue = [NSMutableArray array];
  79. }
  81. + (bool) isUnderDeletion : (id) argObjectID
  82. {
  83.     return [objectsUnderDeletionQueue containsObject:argObjectID];
  84. }

Both delete functions do what is expected – they delete ActiveUsers and ActiveSessions object from database. There is nothing unusual that they do. objectsUnderDeletion array is our way of keeping things in sync: when is busy deleting stuff in background, it prevents our app from repeatedly firing delete commands.

Sign off and Giving Ins:

This tutorial and the code that comes with can serve as bare backbone to your next cutting edge messenger App. You can do your own customizations for Parse user management or UI layout and create your next killer iphone video chat app.

Keep chatting…

Author: Nirav

Scroll to Top