I'm making an app that will use PubNub for a group chat part of the app. I turned on Playback
on my app and I completed the tutorial for setting up the code. I'm confused though, because all the code was in the AppDelegate
, and I have my chat view controller as part of my storyboard. My question is, what setup code do I have to do in my view controller so I can get all the past 100 messages using the historyForChannel:start:end:limit:withCompletion:
method. Would I have to make a new instance of the PubNub client? That doesn't make sense since the user will be switching view controllers and It should be stored in a long life property.
What setup code do I have to do in my view controllers to get the past messages? (To be loaded into a very elaborate tableview setup)
So I figured out a working solution. First, you have to make the PubNub client property public by defining it in the AppDelegate.h
file, not the .m
implementation.
// AppDelegate.h
#import <UIKit/UIKit.h>
#import <PubNub/PubNub.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, PNObjectEventListener>
@property (strong, nonatomic) UIWindow *window;
// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic) PubNub *pnClient;
@end
And don't forget to delete from the AppDelegate.m
#import "AppDelegate.h"
@interface AppDelegate ()
/*
// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic) PubNub *pnClient;
*/ // Delete from here
@end
@implementation AppDelegate
If you want to do notifications and such, keep the AppDelegate
as a listener to the [self.pnClient]
property. If not, just delete <PNObjectEventListener>
from the AppDelegate.h
and [self.pnClient addListener:self];
from your AppDelegate.m
. If you prefer to keep it, just don't delete that stuff.
Now, #import
your AppDelegate
in your ChatViewController.h
or the .m
of you prefer. Then, make your .h
conform to the <PNObjectEventListener>
delegate. The, before you forget, add another client in your .h
or .m
to store the property of your PubNub client in your AppDelegate
. :
// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic) PubNub *pnClient;
Next, in your viewDidLoad
method, add:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.pnClient = appDelegate.pnClient;
[self.pnClient addListener:self];
This code first grabs the AppDelegate
of your app, (so there are no shared instance or singleton things involved). Then, It sets the pnClient
of your app delegate to your "temporary" client in your view controller. (See why we moved the AppDelegate
's client to the .h?) And lastly, it adds self as a listener, so you can do stuff in your view controller.
Thats all there is to it!
I would suggest using your chat controller to populate a UITableView or something else, and the AppDelegate
for handling notifications.