Hide iAd Banner SKScene - objective-c

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];
}
}

Related

iAds still refuse to work

Edit: Here's my AppDelegate as well (part of it)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
GameViewController *gameViewController = [[GameViewController alloc]init];
NSLog(#"NSLOG %#", [[gameViewController view]class]);
_bannerViewController = [[BannerViewController alloc]initWithContentViewController:gameViewController];
self.window.rootViewController = _bannerViewController;
[self.window makeKeyAndVisible];
return YES;
}
I am about to give up. I have tried 5 different ways just these past few days to get literally one single iAd to show correctly and as simple as Apple makes it seem, literally 100% of the time I either see no ad or get an error. I have followed the Apple documentation EXACTLY.
The only clue I have is in these two lines
GameViewController *gameViewController = [[GameViewController alloc]init];
NSLog(#"NSLOG %#", [[gameViewController view]class]);
Which are in my app delegate. The NSLog gives me "UIView". No. Why? Why would that ever be a UIView, it should be an SKView, because GameViewController was pre-written for me by apple for sprite kit. How could that possibly give me the wrong object?
I am getting 'NSInvalidArgumentException', reason: '-[UIView scene]: unrecognized selector sent to instance 0x174191780' which others have recommended to fix by putting the originalContent statement but I already have that and it isn't working.
Banner view controller:
#import "BannerViewController.h"
NSString * const BannerViewActionWillBegin = #"BannerViewActionWillBegin";
NSString * const BannerViewActionDidFinish = #"BannerViewActionDidFinish";
#interface BannerViewController () <ADBannerViewDelegate>
#end
#implementation BannerViewController {
ADBannerView *_bannerView;
UIViewController *_contentController;
}
-(instancetype)initWithContentViewController:(UIViewController *)contentController{
NSAssert(contentController != nil, #"Attempting to initialize a BannerViewController with a nil contentController.");
self = [super init];
if (self != nil) {
_bannerView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
_contentController = contentController;
_bannerView.delegate = self;
}
return self;
}
-(void)loadView{
UIView *contentView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
//Have also tried SKView *contentView = [[SKView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
[contentView addSubview:_bannerView];
[self addChildViewController:_contentController];
[contentView addSubview:_contentController.view];
[_contentController didMoveToParentViewController:self];
self.view = contentView;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return [_contentController preferredInterfaceOrientationForPresentation];
}
-(NSUInteger)supportedInterfaceOrientations{
return [_contentController supportedInterfaceOrientations];
}
-(void)viewDidLayoutSubviews{
CGRect contentFrame = self.view.bounds, bannerFrame = CGRectZero;
bannerFrame.size = [_bannerView sizeThatFits:contentFrame.size];
if(_bannerView.bannerLoaded){
contentFrame.size.height -= bannerFrame.size.height;
bannerFrame.origin.y = contentFrame.size.height;
}else{
bannerFrame.origin.y = contentFrame.size.height;
}
_contentController.view.frame = contentFrame;
_bannerView.frame = bannerFrame;
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave{
[[NSNotificationCenter defaultCenter]postNotificationName:BannerViewActionWillBegin object:self];
return YES;
}
-(void)bannerViewActionDidFinish:(ADBannerView *)banner{
[[NSNotificationCenter defaultCenter]postNotificationName:BannerViewActionDidFinish object:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Game View controller:
#interface GameViewController ()
#property (nonatomic, strong) IBOutlet UIView *contentView;
#end
#implementation GameViewController {
}
-(instancetype)init{
self = [super init];
if (self) {
}
return self;
}
-(void)viewDidLoad{
//self.canDisplayBannerAds = YES;
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
}
-(void)viewDidLayoutSubviews{
}
-(void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
SKView *skView = (SKView*)self.originalContentView;
if (!skView.scene) {
SKScene *scene = [GameScene sceneWithSize:skView.bounds.size];
[skView presentScene:scene];
//skView.showsPhysics = YES;
}
}
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskPortrait;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
I figured it out. The answer, as I thought it would be, was incredibly simple and quite mind-boggling that Apple wouldn't put some sort of warning in their documentation, but then again maybe I am just too much of a noob and we are expected to know these kinds of things.
The answer, is that init was never being called in GameViewController, instead, initWithCoder: was being called. Once I NSLogged the init method and saw it wasn't being called, I figured this out.

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.

About Hide the keyboard

My question is :
When I write a user login UI, because the keyboard hide the password textfield, so I write some code to scroll up the login UI, but when the keyboard is hidden and the UI is scrolled to the old position, I find I touch the textfield which I can't get any response.
registe notification:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillshow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillhide:)
name:UIKeyboardWillHideNotification
object:nil];
_username.delegate = self;
_password.delegate = self;
will show keyboard code:
- (void) keyboardWillshow:(NSNotification *)noti
{
NSDictionary *userInfo = [noti userInfo];
NSValue *keyValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [keyValue CGRectValue];
int height = keyboardRect.size.height;
userInfo = nil;
keyValue = nil;
[UIView animateWithDuration:0.5f animations:^{
self.containView.frame = CGRectMake(0, -height+20, WIDTH/2, HEIGHT/2-20);
}];
}
will hide keyboard code:
- (void)keyboardWillhide:(NSNotification *)noti
{
[UIView animateWithDuration:0.5f animations:^{
self.containView.frame = CGRectMake(0, 20, WIDTH/2, HEIGHT/2-20);
}];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_password resignFirstResponder];
[_username resignFirstResponder];
}
Could some one help me? I use the storyboard to write the code.

ADBannerView Full Ad Orientation Not Changing

I use the code right out of the Apple iAd Suite demo code to implement my banner ad with a tab bar controller. It was working fine until recently, when I noticed that the test ads became more colorful, and not just black rectangles with the words "test ad" in them.
However, I am now seeing that, while the banner view rotates okay, the full ad is only showing in landscape orientation. The rest of the app rotates okay, but no matter what orientation the device is in, the full add only shows in landscape.
I don't see how to control this.
Here is the code:
#import "BannerViewController.h"
NSString * const BannerViewActionWillBegin = #"BannerViewActionWillBegin";
NSString * const BannerViewActionDidFinish = #"BannerViewActionDidFinish";
#implementation BannerViewController
{
ADBannerView *_bannerView;
UIViewController *_contentController;
}
- (id)initWithContentViewController:(UIViewController *)contentController
{
self = [super init];
if (self != nil) {
_bannerView = [[ADBannerView alloc] init];
_bannerView.delegate = self;
_contentController = contentController;
}
return self;
}
- (void)loadView
{
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[contentView addSubview:_bannerView];
[self addChildViewController:_contentController];
[contentView addSubview:_contentController.view];
[_contentController didMoveToParentViewController:self];
self.view = contentView;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return [_contentController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
- (void)viewDidLayoutSubviews
{
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
} else {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
}
CGRect contentFrame = self.view.bounds;
CGRect bannerFrame = _bannerView.frame;
if (_bannerView.bannerLoaded) {
contentFrame.size.height -= _bannerView.frame.size.height;
bannerFrame.origin.y = contentFrame.size.height;
} else {
bannerFrame.origin.y = contentFrame.size.height;
}
_contentController.view.frame = contentFrame;
_bannerView.frame = bannerFrame;
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
[UIView animateWithDuration:0.25 animations:^{
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
}
- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
[[NSNotificationCenter defaultCenter] postNotificationName:BannerViewActionWillBegin object:self];
return YES;
}
- (void)bannerViewActionDidFinish:(ADBannerView *)banner
{
[[NSNotificationCenter defaultCenter] postNotificationName:BannerViewActionDidFinish object:self];
}
#end
In the shouldAutorotateToInterfaceOrientation: method, the interfaceOrientation is portrait, and it is evaluating to true. The full ad still shows in landscape.
What is causing this and how can I control it?
It seems only one orientation is supported in Sandboxing mode.

UIButton disappears when my application returns from running in the background

I have a small project that contains a few UITextFields with a number keypad. When the keyboard is displayed I'm adding a button as a subview for the user to dismiss the keyboard.
However, if the keyboard is active and I close the application, the button I've added will disappear upon relaunching the app. (The app stays inactive, through multitasking, and therefore not quit completely.)
This is the code im using to add the button (my "done" button configured in the xib).
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow)name:UIKeyboardWillShowNotification object:nil];
[super viewDidLoad];
}
- (void)keyboardWillShow{
[[NSNotificationCenter defaultCenter] removeObserver:self];
// We must perform on delay (schedules on next run loop pass) for the keyboard subviews to be present.
[self performSelector:#selector(addHideKeyboardButtonToKeyboard) withObject:nil afterDelay:0];
}
- (void)addHideKeyboardButtonToKeyboard{
// Locate non-UIWindow.
doneButton.hidden=NO;
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
if (!keyboardWindow) return;
// Locate UIKeyboard.
UIView *foundKeyboard = nil;
for (UIView __strong *possibleKeyboard in [keyboardWindow subviews]) {
// iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
if ([[possibleKeyboard description] hasPrefix:#"<UIPeripheralHostView"]) {
possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
}
if ([[possibleKeyboard description] hasPrefix:#"<UIKeyboard"]) {
foundKeyboard = possibleKeyboard;
break;
}
}
if (foundKeyboard) {
[doneButton setImage:[UIImage imageNamed:#"doneupHeb.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"donedownHeb.png"] forState:UIControlStateHighlighted];
doneButton.frame = CGRectMake(-1, 163, 106, 53);
[foundKeyboard addSubview:doneButton];
// Add the button to foundKeyboard.
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[prime resignFirstResponder];
[MothlyReturn resignFirstResponder];
[doneButton removeFromSuperview];
doneButton = nil;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
textField.delegate=self;
//editingField = textField;
if ([prime isFirstResponder]||[MothlyReturn isFirstResponder]){
scroll.contentOffset = CGPointMake(0, 166 );
}
// if ([YearCycle isFirstResponder]){
// scroll.contentOffset = CGPointMake(0, 200);
}
- (IBAction)closeNumpad:(id)sender{
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[prime resignFirstResponder];
[MothlyReturn resignFirstResponder];
scroll.contentOffset = CGPointMake(0, 0);
doneButton.hidden=YES;
}
i fixed the problem with a little help from other questions in the website - for all of you that have or will have the problem - this is the code:
Please note: the button himself are designed in the xib file and not in the code.
the .h file:
BOOL firstTime;
BOOL add;
BOOL keyboardOpened;
IBOutlet UIButton *doneButton;
the .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
firstTime = TRUE;
add = TRUE;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; // Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
// [[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)addButtonToKeyboard {
// create custom button
/* UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:#"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:#"DoneDown.png"] forState:UIControlStateHighlighted];
doneButton.tag = 3;
[doneButton addTarget:self action:#selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];*/
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[keyboard description] hasPrefix:#"<UIPeripheralHostView"] == YES && add){
doneButton.frame = CGRectMake(-1, 163, 106, 53);
[keyboard addSubview:doneButton];
}
}
}
- (void)removeButtonFromKeyboard
{
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, remove the button
if([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES) [[keyboard viewWithTag:3] removeFromSuperview];
}
}
- (IBAction)doneButton:(id)sender {
[loan resignFirstResponder];
[YearCycle resignFirstResponder];
[ageOfCeo resignFirstResponder];
[YearofBusiness resignFirstResponder];
scroll.contentOffset = CGPointMake(0, 0);
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
[self removeButtonFromKeyboard];
firstTime = TRUE;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([ageOfCeo isFirstResponder]||[YearofBusiness isFirstResponder]){
scroll.contentOffset = CGPointMake(0, 166 );
}
// firstResponder = textField;
}
- (void)keyboardDidShow:(id)sender
{
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
NSLog(#"%#",[[UIDevice currentDevice] model]);
[self addButtonToKeyboard];
keyboardOpened = TRUE;
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (![[[UIDevice currentDevice] model] isEqualToString:#"iPad"] && ![[[UIDevice currentDevice] model] isEqualToString:#"iPad Simulator"])
{
[self removeButtonFromKeyboard];
keyboardOpened = FALSE;
}
}
i think your problem because you are removing the observer in the - (void)keyboardWillShow .. try to put this line [[NSNotificationCenter defaultCenter] removeObserver:self]; in the -(void)viewDidUnload