First of all, sorry for my English… I’m developing an iOS application that has an UITabBarController. I want to initialize sockets from this UITabBarController in order to manage any event that occurs inside the application.
The problem is that I don’t know how to do it. With my socket I can send messages to a server and receive them from this server. I would like to receive events if I am in other tab item.
This is my code for creating the socket:
- (void) initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"212.227.52.247", 9191, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
[self activarUsuario];
}
I have a view for sending messages, but I would like to handle events in all the views I have in my UITabBarController, like WhatsApp she you receive a new message…
Can someone help me, please?
I have been searching in Google for days but I haven’t found anything…
Thank you very much!!
Perhaps you could move your socket communication code to another class, maybe the App Delegate or another singleton type class. Whenever you receive events you could post that information using the default
NSNotificationCenteralong with a dictionary of data containing the event you received.Once you do that you can have each of your
UIViewControllerinstances register to receive your notifications using theNSNotificationCenteraddObserver:selector:name:object:method. Any time yourUIViewControllerinstances receive the notification it will call the method you specified in the selector.When you receive an event in your socket code, you can post the notification like this
[[NSNotificationCenter defaultCenter] postNotificationName:@"MY_NOTIFICATION_TYPE" object:sender userInfo:yourDictionaryOfEventData];You can register for the notifications in the
UIViewControllerviewWillAppear:method like so… (if you want to have notifications when view is not visible/loaded you can do this in init)[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedEvent:) name:@"MY_NOTIFICATION_TYPE" object:sender];and finally, don’t forget to unregister for the notifications in the
viewWillDisappear:of yourUIViewController. (or dealloc if you registered for them in init)[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MY_NOTIFICATION_TYPE" object:sender];
NSNotification Apple Docs