NSNotification not being called when UIButton triggered - uibutton

I don't understand why a NSNotification I'm trying to send is not being called when I pulse a UIButton. I'm trying to send an object from a ViewController to other ViewController with Notifications.
My code:
In Viewcontroller.m :
- In Init method:
[self.goPanelRightButton addTarget:self action:#selector(btnMovePanelRight:) forControlEvents:UIControlEventTouchUpInside];
- (IBAction)btnMovePanelRight:(id)sender
{
UIButton *button = sender;
switch (button.tag) {
case 0: {
[self movePanelToOriginalPosition];
break;
}
case 1: {
[self sendModel];
NSLog(#"Entered case 1");
[self movePanelRight];
break;
}
default:
break;
}
}
-(void)sendModel{
[[NSNotificationCenter defaultCenter] postNotificationName:kModelNotification
object:self
userInfo:#{GALLERY_KEY:self.model}];
In ObserverViewController:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:#selector(getModelMain:)
name:kModelNotification
object:nil];
}
}
-(void)getModelMain:(NSNotification *) notification{
NSDictionary *dict = [notification userInfo];
self.model=[dict objectForKey:GALLERY_KEY];
}
Thanks ;)

I resolved with Key Value Coding. Passing the object before I change to the next view:
SEL selector = NSSelectorFromString(#"setModel:");
if ([self.leftPanelViewController respondsToSelector:selector]) {
[self.leftPanelViewController setValue:self.model forKey:#"model"];
}

Related

Hide iAd Banner SKScene

Hi Guys What Do You Think Should I Use In The Handle Notifications (hideAd,showAd) to show and hide my iAd Banner In My Project and here is what i use to show iAd Banner `#import "GameViewController.h"
import "GameScene.h"
#interface GameViewController(){
bool adOnTop;
bool iadsBannerIsVisible;
ADBannerView* theBanner;
}
#end
#implementation GameViewController
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleNotification:) name:#"hideAd" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleNotification:) name:#"showAd" object:nil];
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
skView.multipleTouchEnabled = YES;
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = YES;
// Create and configure the scene.
GameScene *scene = [GameScene sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFit;
// Present the scene.
[skView presentScene:scene];
[self showThinBanner];
}
-(void) showThinBanner {
iadsBannerIsVisible = YES;
theBanner = [[ADBannerView alloc] initWithFrame:CGRectZero];
[theBanner setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
theBanner.delegate = self;
[self.view addSubview:theBanner];
}
- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave {
NSLog(#"Banner view is beginning an ad action");
BOOL shouldExecuteAction = YES; // your app implements this method
if (!willLeave && shouldExecuteAction){
// insert code here to suspend any services that might conflict with the advertisement, for example, you might pause the game with an NSNotification like this...
[[NSNotificationCenter defaultCenter] postNotificationName:#"PauseScene" object:nil]; //optional
}
return shouldExecuteAction;
}
-(void) bannerViewActionDidFinish:(ADBannerView *)banner {
NSLog(#"banner is done being fullscreen");
//Unpause the game if you paused it previously.
[[NSNotificationCenter defaultCenter] postNotificationName:#"UnPauseScene" object:nil]; //optional
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
if (iadsBannerIsVisible == YES) {
[UIView beginAnimations:#"animateAdBannerOff" context:NULL];
// Assumes the banner view is placed at the bottom of the screen.
banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height);
[UIView commitAnimations];
iadsBannerIsVisible = NO;
NSLog(#"banner unavailable");
}
}
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:#"hideAd"])
{
// hide your banner;
}else if ([notification.name isEqualToString:#"showAd"])
{
// show your banner
}
}
Sloved
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:#"hideAd"])
{
// hide your banner;
[theBanner removeFromSuperview];
}else if ([notification.name isEqualToString:#"showAd"])
{
// show your banner
[self.view addSubview:theBanner];
}
}

how to get thumbnail of video url ios

i have tried below code. As result its gets image some time, not in every call of this method.
is there any solution.
-(UIImage *)thumbnailFromVideoAtURL:(NSString *)urlstr
{
NSURL *url = [NSURL URLWithString:urlstr];
AVAsset *asset = [AVAsset assetWithURL:url];
// Get thumbnail at the very start of the video
CMTime thumbnailTime = [asset duration];
thumbnailTime.value = 0;
// Get image from the video at the given time
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:thumbnailTime actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return thumbnail;
}
CustomMoviePlayerVC.h
#interface CustomMoviePlayerVC : UIViewController {
#public
MPMoviePlayerController *mp;
NSURL *movieURL;
}
#property (weak, nonatomic) UIView *playBtn;
- (id)initWithPath:(NSString *)moviePath tag:(int)tag;
- (void)startPlayer;
- (void)pausePlayer;
- (void)stopPlayer;
- (BOOL)isFullScreen;
- (UIImage *)getVideoThumbnail;
- (MPMoviePlaybackState)getVideoPlaybackState;
- (MPMovieLoadState)getVideoLoadState;
- (void)enterFullScreenAnimated:(BOOL)animated;
- (void)exitFullScreenAnimated:(BOOL)animated;
- (void)prepare;
#end
CustomMoviePlayerVC.m
#import "CustomMoviePlayerVC.h"
#interface CustomMoviePlayerVC ()
#end
#implementation CustomMoviePlayerVC
- (BOOL)isFullScreen
{
return mp.isFullscreen;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (id)initWithPath:(NSString *)moviePath tag:(int)tag
{
// Initialize and create movie URL
if (self = [super init]) {
movieURL = [NSURL URLWithString:moviePath];
mp = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
// Set movie player layout
if(tag == 1) {
[mp setControlStyle:MPMovieControlStyleNone];
}
[mp setShouldAutoplay:NO];
[mp setFullscreen:NO];
// May help to reduce latency
[mp prepareToPlay];
// Register that the load state changed (movie is ready)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerLoadStateChanged:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector: #selector(MoviePlayerThumbnailImageRequestDidFinish:)
name: MPMoviePlayerThumbnailImageRequestDidFinishNotification
object: nil];
// registering for playback state change notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:nil];
// registering for playback finish notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
// registering for playback finish notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackWillEnterFullscreen:)
name:MPMoviePlayerWillEnterFullscreenNotification
object:nil];
// registering for playback finish notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackDidExitFullscreen:)
name:MPMoviePlayerDidExitFullscreenNotification
object:nil];
}
return self;
}
- (void)MoviePlayerThumbnailImageRequestDidFinish:(NSNotification*)not
{
}
- (void)enterFullScreenAnimated:(BOOL)animated
{
[mp setFullscreen:YES animated:animated];
}
- (void)exitFullScreenAnimated:(BOOL)animated
{
[mp setFullscreen:NO animated:animated];
}
- (void)moviePlayerLoadStateChanged:(NSNotification *)notification
{
[mp setControlStyle:MPMovieControlStyleEmbedded];
// Unless state is unknown, start playback
if ([mp loadState] != MPMovieLoadStateUnknown) {
// Set frame of movie player
[[mp view] setFrame:self.view.frame];
// Add movie player as subview
[[self view] addSubview:[mp view]];
}
}
- (void)moviePlaybackDidFinish:(NSNotification *)notification
{
[self exitFullScreenAnimated:YES];
if (mp.currentPlaybackTime <= 0.1) {
dispatch_async(dispatch_get_main_queue(), ^{
[mp stop];
[mp play];
[mp pause];
});
}
}
- (void)moviePlaybackStateDidChange:(NSNotification *)notification
{
switch ([self getVideoPlaybackState]) {
case MPMoviePlaybackStatePlaying:
[self.playBtn setHidden:YES];
[self.playBtn setUserInteractionEnabled:NO];
break;
case MPMoviePlaybackStatePaused:
[self.playBtn setHidden:NO];
[self.playBtn setUserInteractionEnabled:YES];
break;
case MPMoviePlaybackStateStopped:
[self.playBtn setHidden:NO];
[self.playBtn setUserInteractionEnabled:YES];
break;
default:
break;
}
}
- (void)moviePlaybackWillEnterFullscreen:(NSNotification *)notification
{
}
- (void)moviePlaybackDidExitFullscreen:(NSNotification *)notification
{
}
- (void)startPlayer
{
[self.playBtn setHidden:YES];
[self.playBtn setUserInteractionEnabled:NO];
if (mp.loadState != MPMovieLoadStateUnknown) {
[mp play];
}
}
- (void)pausePlayer
{
[self.playBtn setHidden:NO];
[self.playBtn setUserInteractionEnabled:YES];
if (mp.loadState != MPMovieLoadStateUnknown) {
[mp pause];
}
}
- (void)stopPlayer
{
[self.playBtn setHidden:NO];
[self.playBtn setUserInteractionEnabled:YES];
if (mp.loadState != MPMovieLoadStateUnknown) {
[mp stop];
}
}
- (UIImage *)getVideoThumbnail
{
if (mp && mp.loadState != MPMovieLoadStateUnknown) {
return [mp thumbnailImageAtTime:0.3 timeOption:MPMovieTimeOptionExact];
}
return nil;
}
- (MPMoviePlaybackState)getVideoPlaybackState
{
return mp.playbackState;
}
- (MPMovieLoadState)getVideoLoadState
{
return mp.loadState;
}
- (void)prepare
{
[mp prepareToPlay];
}
#end
Use getVideoThumbnail to get image from video.

MPMoviePlayerController does not dismiss view when clicking done?

I use a MPMoviePlayerController to play a video from Internet.
player = [player initWithContentURL:[NSURL URLWithString:videoURL]];
player.view.frame = CGRectMake(0, 0, videoView.frame.size.width, videoView.frame.size.height - 20);
[player setControlStyle:MPMovieControlStyleEmbedded];
player.scalingMode = MPMovieScalingModeAspectFit;
[player prepareToPlay];
player.shouldAutoplay = NO;
[videoView addSubview:player.view];
I notified that after I clicked the full screen button (2-arrows-button), I was navigated to the full size video screen. I couldn't restore down the screen by touching the Done button. I even used NSNotification but can't resolve the problem. Here is the Notification code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieEventFullscreenHandler:)
name:MPMoviePlayerWillEnterFullscreenNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieEventFullscreenHandler:)
name:MPMoviePlayerDidEnterFullscreenNotification
object:nil];
}
- (void)movieEventFullscreenHandler:(NSNotification*)notification {
[player setFullscreen:NO animated:NO];
[player setControlStyle:MPMovieControlStyleEmbedded];
}
How can I dismiss that video screen by touching the Done button? Thanks guys.
You can use the notification of MPMoviePlayerPlaybackDidFinishNotification to observe the done button.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playObserver:)name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
and then,make a judge of quitting.
- (void) playObserver:(NSNotification *)notification
{
MPMoviePlayerController* player = moviePlayerView.moviePlayer;
if (player == [notification object]) {
if (_invalidVideoCount > MOVIE_TRY_TIMES) {
[self dismissViewController];
}
_invalidVideoCount++;
int reason = [[[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
//Whether continuous playback
if (![SINGLETON_CALL(SystemInfoManager) boolValueForKey:UserContinuousPlayEnableKey]) {
[self playFinishWithForce:YES];
return;
}
switch (reason) {
case MPMovieFinishReasonUserExited:
[self playFinishWithForce:YES];
break;
case MPMovieFinishReasonPlaybackError:
[self playFinishWithForce:YES];
break;
case MPMovieFinishReasonPlaybackEnded:
movieTryTimes = 0;
[self playFinishWithForce:NO];
break;
default:
break;
}
}
}
and the last.
- (void)playFinishWithForce:(BOOL)force
{
FileInfoItem *item = ARRAY_OBJECT_AT_INDEX(_playlist, _currentIndex);
BOOL quit = force || !item;
if (quit) {
[self dismissViewController];
} else {
[self playMovieWithItem:item];
}
}
Also you can use the notification of MPMoviePlayerPlaybackStateDidChangeNotification to make any observe.something detail see MPMoviePlayerController.h or https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/Reference.html
I have found the problem. That's I laid [player stop] in the viewWillDisAppear so can't handle the notification. I fixed temporary by changing it to [player pause]. I appreciated any kind of your helps.

Test NSNotification delivery

I'm trying to make sure the NSNotification gets sent after reportIssue is called.
I get this error:
error: -[APHIssueComposerTests testPopulatedIssueIsReceived] : OCMockObject[APHIssueComposerTests]: expected method was not invoked: reportIssueNotificationReceived
In APHIssueComposer.m:
- (void) reportIssue {
APHIssue* issue = [self issue];
NSNotification* notification = [NSNotification notificationWithName:APHLogDataObjectNotification object:issue];
[[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostWhenIdle];
[self discardIssue];
}
In APHIssueComposerTests.m:
- (void)setUp
{
[super setUp];
self.mockObserver = [OCMockObject mockForClass:[self class]];
[[NSNotificationCenter defaultCenter] addObserver:self.mockObserver
selector:#selector(reportIssueNotificationReceived)
name:APHLogDataObjectNotification
object:nil];
self.issueComposer = [[APHIssueComposer alloc] initWithTempDirectory:#"/my/fake/directory"];
}
- (void)testPopulatedIssueIsReceived
{
[[self.mockObserver expect] reportIssueNotificationReceived];
self.issueComposer.message = #"fake message.";
[self.issueComposer reportIssue];
[mockObserver verify];
[[NSNotificationCenter defaultCenter] removeObserver:mockObserver name:APHLogDataObjectNotification object:nil];
}
- (void)tearDown
{
[super tearDown];
[[NSNotificationCenter defaultCenter] removeObserver:mockObserver name:APHLogDataObjectNotification object:nil];
}
Why doesn't the mock object receive the notification?
The problem is that enqueueNotification is asynchronous.

iOS: Passing data between views

I have two views which are created programmatically. Let's name them view1 and view2. In view1 there is a picker and a button. The idea is when the user choose value and press the button selected value to be accessable from view2. For this I use NSNotificationCenter. Here is some code.
view1.m
-(void)registerNotification
{
NSDictionary *dict = [NSDictionary dictionaryWithObject:self.selectedOption forKey:#"data"];
[[NSNotificationCenter defaultCenter]
postNotificationName:#"pickerdata"
object:self
userInfo:dict];
}
-(void)loadSecondView
{
self.secondView = [[secondViewController alloc]init];
[self.view addSubview:self.secondView.view];
[self registerNotification];
[self.secondView release];
}
view2.m
-(id)init
{
if(self = [super init])
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(reciveNotification:)
name:#"pickerdata" object:nil];
}
return self;
}
-(void)reciveNotification:(NSNotification *)notification
{
if([[notification name] isEqualToString:#"pickerdata"])
{
NSLog(#"%#", [NSString stringWithFormat:#"%#", [[notification userInfo] objectForKey:#"data"]]); // The output of NSLog print selected value
// Here is assignment to ivar
self.selectedValue = [NSString stringWithFormat:#"%#", [[notification userInfo] objectForKey:#"data"]];
}
}
The problem starts here. The logic which is interested of that value is implemented in loadView method. The problems is that loadView is executed before reciveNotification method and selectedValue does not contain needed information yet.
What to do so the information provided from NSNotificationCenter to be accessible from loadView method ?
I don't know if I fully understand your question, but wouldn't it be easier to pass the value directly to the viewController instead of dealing with notifications?
-(void)loadSecondView
{
self.secondView = [[secondViewController alloc]init];
self.secondView.selectedValue = self.selectedOption;
[self.view addSubview:self.secondView.view];
[self.secondView release];
}