Pass String Using NSNotifcation in iOS - ios

I am pretty sure this question has been asked and answered, but I am not sure what I am doing wrong that I am not being able to get the method called from NSNotificationCenter. I have two classes :
Sign In Class And Calendar View Class
I want to pass single user credential from SignIn to Calendar. I have put the Calendar in SWRevealController. NSNotification is being called but the trigger method is not called for some reason.
Sign In
- (IBAction)signIn:(id)sender {
_passWord = _password.text;
NSLog(#"%# %#",_userName,_passWord);
[[NSNotificationCenter defaultCenter] postNotificationName: #"Password" object: _passWord];
[self performSegueWithIdentifier:#"signIn" sender:self];
}
Calendar
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *ppnImage = [UIImage imageNamed:#"PPNImage.png"];
NSLog(#"came here");
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(triggerAction:) name:#"Password" object:nil];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
events = [[NSMutableArray alloc]init];
[_indicator startAnimating];
self.tableView.delegate = self;
//Creating a background queue
web = [WebRequests sharedInstance];
web.delegate = self;
[web loginView];
}
-(void) triggerAction: (NSNotification *) notification {
NSLog(#"Does not call this");
}
Here
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(triggerAction:) name:#"Password" object:nil];
is called
BUT the below method is not called
-(void) triggerAction: (NSNotification *) notification
{
NSLog(#"Does not call this");
}
Really appreciate if somebody can suggest me what am I doing wrong

Related

How to hide google ads in Objective c

In my project , i have implemented Google-Mobile-Ads SDK. I have followed all the steps with are written in the google site. I am able to access the google ad in all my view controllers as i have coded it in my AppDelegate.
Now , i want it to hide it from the first view controller (like we can hide navigationbar), how to implement this ?
In have coded this for google ads in AppDelegate`s DidFinishLaunchingMethod:-
bannerView=[[GADBannerView alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height-50, self.window.frame.size.width, 50)];
[self.window addSubview:bannerView];
bannerView.adUnitID = #"ca-app-pub-8809802355107737/4999307809";
bannerView.rootViewController = self.window.rootViewController;
bannerView.delegate=self;
GADRequest *request = [GADRequest request];
request.testDevices = #[ #"eba07768136b615eee7c1f8acde25c1b",kGADSimulatorID ];
[bannerView loadRequest:request];
[self.window makeKeyAndVisible];
return YES;
I have this method also in appDelegate class :-
- (void)adViewDidReceiveAd:(GADBannerView *)view;
{
if (container.view.frame.size.height==self.window.frame.size.height-50) {
}
else
{
CGRect navFrame = container.view.frame;
navFrame.size.height -= 50;
container.view.frame = navFrame;
}
NSLog(#"asdhaskda");
}
in firstViewController:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] postNotificationName:#"HIDEBANNER" object:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] postNotificationName:#"SHOWBANNER" object:nil];
}
In AppDelegate.m file, in didFinishLaunchingWithOptions:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(hideBanner) name:#"HIDEBANNER" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(showBanner) name:#"SHOWBANNER" object:nil];
Also implement those 2 functions. I'm not sure what exactly must be in those functions. Maybe something like this:
-(void)showBanner{
[bannerView setHidden:NO];
//this is from your code
if (container.view.frame.size.height==self.window.frame.size.height-50) {
}
else
{
CGRect navFrame = container.view.frame;
navFrame.size.height -= 50;
container.view.frame = navFrame;
}
}
-(void)hideBanner{
[bannerView setHidden:YES];
CGRect navFrame = container.view.frame;
navFrame.size.height = self.window.frame.size.height;
container.view.frame = navFrame;
}
There are many methods to do that. You can use, for example, NSNotificationCenter.
In your AppDelegate.m file in didFinishLaunchingWithOptions function:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(hideBanner) name:#"HIDEBANNER" object:nil];
Also in AppDelegate.m add the following function:
-(void)hideBanner{
[bannerView setHidden:YES];
}
And somewhere in you project, when you need to hide banner just call this:
[[NSNotificationCenter defaultCenter] postNotificationName:#"HIDEBANNER" object:nil];
AdMob Integration Full Code.
AppDelegate.h
// Write This Code in AppDelegate.h File Start
#import GoogleMobileAds;
#pragma mark - Admob
#property (strong, nonatomic) GADBannerView *bannerView;
-(void)loadAdmob:(UIViewController *)vc;
// End
AppDelegate.m
// Write This Code in AppDelegate.m File Start
#pragma mark - Admob Methods
-(void)loadAdmob:(UIViewController *)vc{
self.bannerView = [[GADBannerView alloc] initWithFrame:CGRectMake(0, vc.view.frame.size.height-kBannerHeight, vc.view.frame.size.width, kBannerHeight)];
[vc.view addSubview:self.bannerView];
self.bannerView.hidden = YES;
//### Load Banner Ad view #####
// Replace this ad unit ID with your own ad unit ID.
self.bannerView.adUnitID = #"ca-app-pub-####"; // Botttom banner
self.bannerView.rootViewController = vc;
GADRequest *request = [GADRequest request];
// Requests test ads on devices you specify. Your test device ID is printed to the console when
// an ad request is made.
#ifdef DEBUG
request.testDevices = #[kGADSimulatorID];
//[Note: Comment this line for release build]
#endif
[self.bannerView loadRequest:request];
}
// Add this code in Viewcontroller.m file
[APP_DELEGATE loadAdmob:self];
// Add this line in PrefixHeader.pch
#define APP_DELEGATE (AppDelegate*)[[UIApplication sharedApplication] delegate]
#define kBannerHeight (IS_IPAD ? 65.0 : 49.0)

MPMoviePlayerController crash when start play a video on iOS 6

I'm using MPMoviePlayerViewController to play video. In my app I am playing video(s) that are in the app, using the standard MPMoviePlayerController class. It works fine on iOS 7 and 8
The first time around around this works great, however after watching 1 video if you try and watch something else the app crashes on MPMoviePlayerController's play method with the error:
: CGContextSaveGState: invalid context 0x0
: CGContextClipToRect: invalid context 0x0
: CGContextTranslateCTM: invalid context 0x0
: CGContextDrawShading: invalid context 0x0
: CGContextRestoreGState: invalid context 0x0
*** -[MPMoviePlayerController retain]: message sent to deallocated instance 0x1e5718b0
I can not figure out why this is happening.
Here is my code:
AFPlayerViewController.h
#property (strong, nonatomic) MPMoviePlayerViewController *playerViewController;
- (id)initWithContentURL:(NSString*)movieUrl
andSubtitlePath:(NSString*)subPath
withTypeServer:(NSString*)serverType
withName:(NSString*)name
withEpisodeId:(NSString*)episodeId
withFilmId:(NSString*)filmId
withDuration:(NSInteger)targetDuration
withSeason:(NSString*)seasonId;
AFPlayerViewController.m
#synthesize playerViewController;
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (_movieURL) {
self.playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL: _movieURL];
self.playerViewController.moviePlayer.initialPlaybackTime = -1.f;
self.playerViewController.moviePlayer.shouldAutoplay = NO;
[self.playerViewController.moviePlayer setControlStyle:MPMovieControlStyleNone];
[self.playerViewController.moviePlayer setFullscreen:NO animated:YES];
self.playerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self.playerViewController.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:self.playerViewController.view];
[NSLayoutConstraint alightTopBotLeftRight:self.playerViewController.view inView:self.view];
[self.playerViewController.moviePlayer prepareToPlay];
[self.playerViewController.moviePlayer play];
[self receiveNotificationPlayerViewController];
}
}
- (void)receiveNotificationPlayerViewController {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(durationAvailable:)
name:MPMovieDurationAvailableNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadStateDidChange:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playbackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(sourceTypeAvailable:)
name:MPMovieSourceTypeAvailableNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(readyForDisplay:)
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(orientationDidChange:)
name:UIDeviceOrientationDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didFinishAVideo:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.playerViewController.moviePlayer];
}
- (void) durationAvailable: (NSNotification*) notification {
NSLog(#"1");
}
- (void) loadStateDidChange: (NSNotification*) notification {
NSLog(#"2");
if ([self.playerViewController.moviePlayer loadState] != MPMovieLoadStateUnknown) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:nil];
}
}
- (void) playbackStateDidChange: (NSNotification*) notification {
NSLog(#"3");
switch (self.playerViewController.moviePlayer.playbackState) {
case MPMoviePlaybackStateSeekingForward:
case MPMoviePlaybackStateSeekingBackward:
break;
case MPMoviePlaybackStatePaused: {
NSLog(#"pause");
}
break;
case MPMoviePlaybackStateStopped: {
NSLog(#"stop");
}
break;
case MPMoviePlaybackStateInterrupted:{
NSLog(#"interrupted");
}
break;
case MPMoviePlaybackStatePlaying: {
NSLog(#"playing");
}
break;
default:
break;
}
}
- (void) sourceTypeAvailable: (NSNotification*) notification {
NSLog(#"4");
}
- (void) readyForDisplay: (NSNotification*) notification {
NSLog(#"5");
}
- (void)orientationDidChange: (NSNotification*)notification {
NSLog(#"6");
}
- (void)didFinishAVideo:(NSNotification*)notification {
[self removeNotification];
}
- (void)removeNotification {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMovieDurationAvailableNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMovieSourceTypeAvailableNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:self.playerViewController.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIDeviceOrientationDidChangeNotification
object:self.playerViewController.moviePlayer];
}
AppDelegate.h
#property (strong, nonatomic) AFPlayerViewController *player;
AppDelegate.m
+ (AppDelegate *)shareInstance{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (UIViewController *)currentVisibleController{
id rootController = self.window.rootViewController;
if ([rootController isKindOfClass:[UINavigationController class]]) {
UINavigationController *navigationController = (UINavigationController *)rootController;
return navigationController.topViewController;
}
if ([rootController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabbarController = (UITabBarController *)rootController;
id topViewController = [tabbarController.viewControllers objectAtIndex:tabbarController.selectedIndex];
if ([topViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController *navi = (UINavigationController *)topViewController;
return navi.topViewController;
}
return topViewController;
}
return self.window.rootViewController;
}
When I'd like to play a video:
[AppDelegate shareInstance].player = [[AFPlayerViewController alloc] initWithContentURL:link
andSubtitlePath:subtitle
withTypeServer:serverType
withName:nameFilm
withEpisodeId:epObject.episodeId
withFilmId:filmId
withDuration:lastDuration
withSeason:epObject.id_season];
[[AppDelegate shareInstance].currentVisibleController presentViewController:[AppDelegate shareInstance].player animated:NO completion:^{
}];
You may well be getting the error because of notifications being sent to a removed controller object as #Bannings says. Nevertheless, I have a couple of other suggestions that will improve your code (and I am fairly sure will remove the error).
Firstly, the documentation says that you should register for the MPMoviePlayerLoadStateDidChangeNotification and use the loadState method to determine when the movie is ready to start playing. I strongly suggest that you do that.
Secondly, you are instantiating a MPMoviePlayerController every time your view appears. I would suggest that you create a single AFPlayerViewController and a single MPMoviePlayerController. Present the same AFPPlayerViewController whenever you wish to play another movie.
When you first instantiate the MPMoviePlayerController, you will need a a URL, for its init method, but subsequent movies can be started using the contentURL property of MPMoviePlayerController
A side advantage of my suggestion is that it will be very easy for a user to pause a movie, go to a different view, and then quickly resume when they return to the movie view.
Have you called the removeNotification if you try and watch something else? try to add viewDidDisappear:
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self removeNotification];
}
I think I see the real problem here: you should be using MPMoviePlayerController not MPMoviewPlayerViewController. Make that change, and see if the crash disappears. My suggestion about loadState should be followed too.

Objective C - Lost with retain cycles

upon dismissing my VC, I noticed I am not releasing everything from memory. I'm very lost as to how I would go about finding my retain cycle. I am using an NSTimer and NSNotificationCenter, but I make sure to invalidate and removeObservers before exiting, and I made sure of using a weak delegate.
Where else could my retain cycles be occurring? In animation blocks? Like this?
[UIView animateWithDuration:.1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.setListTableViewVertConst.constant = 0;
self.setListTableViewHeightConst.constant = 264;
} completion:^(BOOL finished) {
}];
When using GCD I make sure to use weakSelf.
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.remotePasswordTextField resignFirstResponder];
});
Thanks for any help.
EDIT:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
//Send the room code to be displayed on the respective view controllers.
if ([segue.identifier isEqualToString:#"toSetListRoomVC"]) {
SetListRoomViewController *setListVC = segue.destinationViewController;
setListVC.roomCode = self.roomCodeTextField.text;
}
}
viewWIllApear
[super viewWillAppear:YES];
self.socket = [[SocketKeeperSingleton sharedInstance]socket];
self.socketID = [[SocketKeeperSingleton sharedInstance]socketID];
NSString *roomCodeAsHost = [[SocketKeeperSingleton sharedInstance]hostRoomCode];
/////////HOST/////////
if ([[SocketKeeperSingleton sharedInstance]isHost]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveHostSongAddedNotification:)
name:kQueueAdd
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveUserJoinedNotification:)
name:kUserJoined
object:nil];
NSLog(#"User is the host of this room");
self.isHost = YES;
[self viewForNoCurrentArtistAsHost];
self.roomCodeLabel.text = roomCodeAsHost;
if (!self.hostQueue) {
self.hostQueue = [[NSMutableArray alloc]init];
}
if (!self.hostCurrentArtist) {
self.hostCurrentArtist = [[NSMutableDictionary alloc]init];
}
if (!self.player) {
self.player = [[AVPlayer alloc]init];
}
if (!self.timer) {
self.timer = [[NSTimer alloc]init];
}
}
///////NOT HOST///////
else {
// Add a notifcation observer and postNotification name for updating the tracks.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveQueueUpdatedNotification:)
name:kQueueUpdated
object:nil];
//Add a notifcation observer and postNotification name for updating current artist.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveCurrentArtistUpdateNotification:)
name:kCurrentArtistUpdate
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveOnDisconnectNotification:)
name:kOnDisconnect
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveHostDisconnectNotification:)
name:kHostDisconnect
object:nil];
//Add some animations upon load up. Purple glow and tableview animation.
double delay = .4;
[self purpleGlowAnimationFromBottomWithDelay:&delay];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationBottom];
//Set Current artist, if there is one.
NSDictionary *currentArtist = [[SocketKeeperSingleton sharedInstance]currentArtist];
[self setCurrentArtistFromCurrentArtist:currentArtist];
//Set the current tracks, if there is one.
NSArray *setListTracks = [[SocketKeeperSingleton sharedInstance]setListTracks];
if (setListTracks) {
self.tracks = setListTracks;
}
}
}
tableVIEWs
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView.tag == 1) {
if (self.isHost) {
return [self.hostQueue count];
}
else return [self.tracks count];
}
else return [self.searchTracks count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
I noticed you are using the word "popOut" in some comments, so I'm going to assume that you are using a navigation controller.
If that is the case, your view controller is retained by the nav controller it's been embedded in and is not released. The nav controller needs to hold a reference to your VC (see UINavigationController.viewControllers)so that it can get back to it when you pop out the top/next VC in the hierarchy.
This is expected behavior.
In this code sample you are not using __weak for self
[UIView animateWithDuration:.1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.setListTableViewVertConst.constant = 0;
self.setListTableViewHeightConst.constant = 264;
} completion:^(BOOL finished) {
}];
However, at a glance this does not seem to be creating a retain cycle. The code you posted doesn't seem to have any, so it's probably somewhere else. Are you sure you have retain cycles?
Anyway, try instrumenting you app. It might help.

iPad UIKeyboard Hide / Resign / Dismiss Button Event Handler?

Can you see the button in the bottom right of the iPad keyboard?
Well I want access to the event handler for that button, Because, I have some logic that I need to administer when specifically THAT button is pressed.
My attempted solution included using the UIKeyboardWillHideNotification notification like so:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(hideKeyboardTapped:)
name:UIKeyboardWillHideNotification
object:nil];
However this is called everytime the keyboard is dismissed, including when search cancel button is pressed, with a gesture tap on the background, etc; all of which have slightly different logic.
So I just need to have one set of logic for when that specific "hide keyboard" button is pressed.
The UIKeyboard is activated by a UISearchBar (for those of you who need extra info).
Any help would be greatly appreciated; and I'll answer any questions you may have.
There is not an official, Apple-sanctioned way to do this.
If you don't mind mucking around with private classes, which could get you rejected from the App Store, there is an unsupported method. Basically, you listen for changes to the keyboard's activeKey property, and if the new active key has a name of "Dismiss-Key", then the dismiss key was tapped:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:#"activeKey"])
{
id activeKey = [object valueForKey:keyPath];
NSString *keyName = [activeKey valueForKey:#"name"];
if ([keyName isEqualToString:#"Dismiss-Key"])
{
[self didTapDismissKey];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardDidShow:(NSNotification *)notification
{
// Search for the UIKeyboardLayoutStar class, which seems to manage layout for the keyboard, and observe its activeKey property
UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
[self traverseViewHierarchyWithView:topWindow block:^(UIView *view, BOOL *stop) {
if ([view isKindOfClass:NSClassFromString(#"UIKeyboardLayoutStar")])
{
[view addObserver:self forKeyPath:#"activeKey" options:0 context:NULL];
}
}];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
// Don't forget to remove the controller as an observer!
UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
[self traverseViewHierarchyWithView:topWindow block:^(UIView *view, BOOL *stop) {
if ([view isKindOfClass:NSClassFromString(#"UIKeyboardLayoutStar")])
{
[view removeObserver:self forKeyPath:#"activeKey"];
}
}];
}
- (BOOL)traverseViewHierarchyWithView:(UIView *)view block:(void (^)(UIView *, BOOL *))block
{
BOOL stop = NO;
block(view, &stop);
if (stop)
{
return YES;
}
for (UIView *subview in view.subviews)
{
if ([self traverseViewHierarchyWithView:subview block:block])
{
return YES;
}
}
return NO;
}
- (void)didTapDismissKey
{
NSLog(#"Dismiss key tapped");
}
Tested on the iOS 7 iPad simulator and it works.
I don't know if you can put a listener to a single button of the keyboard, but you can try to set some Booleans on the views, that can turn on/off the events that you want or don't want to handle (I would approach it like that), for example:
Add a custom notification observer/listener at the class where you
want to execute the method of the event.
Add the Apple default Keyboard Hide listener on the controller where the notification will be triggered.
Then, on the views that can trigger the event... Set the booleans to activate/deactivate the event action
#Some Other Class
-(void)viewWillAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(doSomething)
name:#"doSomethingNotification"
object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"doSomethingNotification" object:nil];
}
#Trigger Class
-(void)viewWillAppear:(BOOL)animated{
self.isNotificationNeeded = NO;
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(onKeyboardHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)onKeyboardHide:(id)sender{
//When your event is Happening
if (self.isNotificationNeeded == YES) {
NSNotification *n = [NSNotification notificationWithName:#"doSomethingNotification" object:nil];
[[NSNotificationCenter defaultCenter] postNotification:n];
self.isNotificationNeeded = NO;
}
}
-(void)userClickedCancelButton{
//If this is a keyboard hide event that you don't want to trigger
self.isNotificationNeeded = NO;
}
//SearchBarDelegate
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
self.isNotificationNeeded = YES; //If your event can happen from here
return YES;
}

NSNotificationCenter doesn't work

I do notifications like this: I have code in mainView:
- (void)viewDidLoad
{
CGRect view1Hrame;
view1Hrame.origin.x = 160;
view1Hrame.origin.y = 215;
view1Hrame.size = self.currenWeatherView.frame.size;
weatherViewController *view1 = [[weatherViewController alloc] initWithForecast:[[Forecast alloc] initWithForecastInCurrentLocation]];
[[NSNotificationCenter defaultCenter] addObserver:view1 selector:#selector(forecastChanged) name:#"forecastChanged" object:nil];
view1.view.backgroundColor = [UIColor colorWithRed:0 green:255 blue:0 alpha:0.06];
[currenWeatherView addSubview: view1.view];
}
in Forecast class:
[[NSNotificationCenter defaultCenter] postNotificationName:#"forecastChanged" object:nil];
in weatherViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(forecastChanged) name:#"forecastChanged" object:nil];
// Do any additional setup after loading the view from its nib.
}
It does not work. What did I do wrong?
if you want to call notification in weatherViewController then you need to define this class's viewDidLoad method.
Make sure you are calling viewDidLoad of this viewController.

Resources