I implemented the AdMob Interstitial ad in my project and it works well. Now I want the AdMob Interstitial ad to only appear for every fifth game and not after every single game. Can someone help me?
Here is my code for the Admob in my GameViewController:
- (void)viewDidLoad {
[super viewDidLoad];
//addInterstitial
self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:#"ca-app-pub-XXXXXXXXXX/XXXXXXXXXX"];
GADRequest *request = [GADRequest request];
request.testDevices = #[#"XXXXXXXXXXXXXXXXXXXXXXXXXX"];
[self.interstitial loadRequest:request];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(handleNotification:) name:#"showAd" object:nil]; }
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:#"showAd"]) {
if ([self.interstitial isReady]) {
[self.interstitial presentFromRootViewController:self]; }
UPDATE:
I have this code in the GameViewController:
- (void)viewDidLoad {
[super viewDidLoad];
//addInterstitial
if ([[NSUserDefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] == nil){
NSNumber *number = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: number forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
if ([[[NSUserDefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue] >= 5){
[self callAd];
self.interstitial = [self createAndLoadInterstitial];
NSNumber *number = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: number forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)handleNotification:(NSNotification *)notification {
if ([notification.name isEqualToString:#"showAd"]) {
if ([self.interstitial isReady]) {
[self.interstitial presentFromRootViewController:self];
}
}
}
- (void) callAd{
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(handleNotification:) name:#"showAd" object:nil];
}
- (GADInterstitial *)createAndLoadInterstitial {
self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:MyAdUnitID2];
self.interstitial.delegate = self;
GADRequest *request2 = [GADRequest request];
request2.testDevices = #[#"XXXXXXXXXXXXXXXXXXXXXX"];
[self.interstitial loadRequest:request2];
return self.interstitial;
}
- (void)interstitialDidDismissScreen:(GADInterstitial *)interstitial {
self.interstitial = [self createAndLoadInterstitial];
}
And in the GameScene.m this code:
- (void)showGameOver{
//addInterstitial
int score = [[[NSUserDefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue]+1;
NSNumber *newNumber = [NSNumber numberWithInt:score];
[[NSUserDefaults standardUserDefaults] setObject:newNumber forKey:GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSNotificationCenter defaultCenter] postNotificationName:#"showAd" object:nil];
Use NSUserDefaults:
- (void) callAd
{
// Code to call your ad here
}
- (void) viewDidLoad
{
// If you haven't played yet, sets to 0
if ([[NSUserdefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] == nil){
NSNumber *num = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: num forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// If you have played
if ([[[NSUserdefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue] >= 5){
[self callAd]; // ad is called
NSNumber *num = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: num forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize]; // resets to zero
}
}
And whenever a game is over:
int score = [[[NSUserdefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue]
+ 1;
NSNumber *newNumber = [NSNumber numberWithInt:score];
[[NSUserDefaults standardUserDefaults] setObject:newNumber forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize]; // Sets to new value
The key can be anything really. At the top of your .m file put:
#define GAME_AMOUNT_KEY #"Game Amount Key"
UPDATE
Change:
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:#"showAd"]) {
if ([self.interstitial isReady]) {
[self.interstitial presentFromRootViewController:self];
}
To:
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:#"showAd"]) {
if ([self.interstitial isReady]) {
if ([[[NSUserDefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue] >= 5){
[self.interstitial presentFromRootViewController:self];
NSNumber *number = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: number forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
And change (in ViewDidLoad):
if ([[[NSUserDefaults standardUserDefaults] objectForKey:GAME_AMOUNT_KEY] intValue] >= 5){
[self callAd];
self.interstitial = [self createAndLoadInterstitial];
NSNumber *number = [NSNumber numberWithInt:0];
[[NSUserDefaults standardUserDefaults] setObject: number forKey: GAME_AMOUNT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
To
[self callAd];
self.interstitial = [self createAndLoadInterstitial];
Related
I have successfully removed ads from the app with an in app purchase.
The problem is that if I close the app and reopen. The ads start up again.
I have 2 main scenes. The GameOverScene and the GameScene. The In App Purchase happens in the GameOverScene.
GameOverScene.m :
- (void)OnRemoveADS {
[self showPurchaseAlert: IAP_Q_RemoveADS :0];
g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: #"REMOVEADS"];
// For HZInterstitialAd, HZVideoAd, and HZIncentivizedAd, just check the BOOL to see if an ad should be shown
if (!g_bRemoveADS) {
[HZInterstitialAd show];
[self removeBannerAds];
[self disableAds];
NSLog(#"Disable ads is called");
}
}
- (void)removeBannerAds {
HZBannerAdOptions *options = [[HZBannerAdOptions alloc] init];
[HZBannerAd placeBannerInView:self.view
position:HZBannerPositionBottom
options:options
success:^(HZBannerAd *banner) {
if (g_bRemoveADS) { // case (2)
// Just discard the banner
[banner setHidden: YES];
[banner removeFromSuperview];
banner = nil;
//_currentBannerAd = banner;
NSLog(#"Banner ad removed!GameOverScene");
} else {
// Keep a reference to the current banner ad, so we can remove it from screen later if we want to disable ads.
_currentBannerAd = banner;
}
NSLog(#"Ad Shown! GameOverScene");
}
failure:^(NSError *error) {
NSLog(#"Error = %#",error);
}];
}
- (void)disableAds {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"REMOVEADS"];
[_currentBannerAd removeFromSuperview]; // case (3)
}
GameScene.m :
-(id) init {
if (self = [super init]) {
if (!g_bRemoveADS) {
g_bRemoveADS=FALSE;
[[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:#"REMOVEADS"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
g_bRemoveADS=TRUE;
[[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:#"REMOVEADS"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
The way I'm trying to solve it is by using the same code from the GameOverScene.m in the AppDelegate.m that way when the app starts up it will remove the ads.
AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: #"REMOVEADS"];
if (!g_bRemoveADS) {
[HZInterstitialAd show];
[self disableAds];
NSLog(#"Disable ads is called");
}
}
Out of my perspective you have one negation to much.
if (!g_bRemoveADS) { should be replaced with if (g_bRemoveADS) { in GameOverScene.m.
if (g_bRemoveADS) {
[HZInterstitialAd show];
[self removeBannerAds];
[self disableAds];
NSLog(#"Disable ads is called");
}
g_bRemoveADS evaluates to TRUE when the respective user-default is set. When it is set, then you call the removeBannerAds stuff etc. which seems to be the deactivation action.
You have to synchronise your NSUserDefaults after changing changing a value in your disableAds method with:
[[NSUserDefaults standardUserDefaults]synchronize];
sorry if the title is a bit sloppy or confusing, I'll try to explain it a bit more detailed.
I have a function in my app which allows users to only use it 10 times a day. The code below handles the counting per day which is actually working good except that the user always have to press twice on a new loop before it's getting called.
I think it has something to do with the fabs function, or what could be the reason the user has to press twice on a new loop?
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = #"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:#"perDay"];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"tenPerDay"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"perDay"];
}else{
if (count % 11 == 0) {
[UIAlertView showWithTitle:#"Daily Limit Exceeded"
message:#"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:#"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
// do something here... (Have to press twice on a new loop before it's getting called)
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = #"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"tenPerDay"];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
}else{
[self counterNew];
}
}
-(void)counterNew{
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:#"perDay"];
if (count > 10) {
[UIAlertView showWithTitle:#"Daily Limit Exceeded"
message:#"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:#"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
//Do something here...
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
I'm trying to make a function that login and logout the user when i click on the segmented button in the settings of my app. when the user clicks on Yes and the user is not yet login to Facebook, I'm opening a session and make the user login using safari, and when the user clicks on the No button, i want the app to logout the user and re-enter its email and password when the Yes button is clicked again.
and the code is this:
- (IBAction)fbSegmentTapped:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex)
{
case 0:{
if (FBSession.activeSession.isOpen) {
//Session is active
NSLog(#"Active 1");
if ([[NSUserDefaults standardUserDefaults] valueForKey:FB_TOKEN] !=nil) {
[self sendPostRequestToAPI_Yes];
}else{
NSLog(#"FB Token null");
}
} else {
// try to open session with existing valid token
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"public_profile", #"email", #"user_friends",
nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permissions];
[FBSession setActiveSession:session];
if([FBSession openActiveSessionWithAllowLoginUI:NO]) {
//Session is active
NSLog(#"Active 2");
if ([[NSUserDefaults standardUserDefaults] valueForKey:FB_TOKEN] !=nil) {
NSLog(#"Move to Yes function");
[self sendPostRequestToAPI_Yes];
}else{
NSLog(#"You nid to login the user");
[self userLogin];
}
} else {
// you need to log the user
[self userLogin];
dataClass.fb_flag = #"false";
NSLog(#"user must login first");
}
}
break;
}
case 1:{
//No
NSLog(#"Clear the token and remove the session");
[self sendPostRequestToAPI_No];
break;
}
default:
break;
}
}
this function is when the user clicks no
-(void) sendPostRequestToAPI_No{
NSDictionary * dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: FB_PROVIDER, [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], nil]
forKeys:[NSArray arrayWithObjects:#"name",#"user_id", nil]];
[webServiceController postRequestFromUrl:[NSString stringWithFormat:#"%#%#", ROOT_SERVER_URL, FB_SETTINGS_NO_URL] withDictionary:dict2];
}
and this is for Yes
-(void) sendPostRequestToAPI_Yes{
NSLog(#"%# - %# - %# - %#", [[NSUserDefaults standardUserDefaults] valueForKey:FB_EMAIL], [[NSUserDefaults standardUserDefaults] valueForKey:FB_PROVIDER_ID], [[NSUserDefaults standardUserDefaults] valueForKey:FB_TOKEN], [[NSUserDefaults standardUserDefaults] valueForKey:SESSION_TOKEN]);
NSLog(#"Provider ID: %# and Email: %#", [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], [[[NSUserDefaults standardUserDefaults] valueForKey:FB_USER_DETAILS] valueForKey:#"email"]);
if ([[NSUserDefaults standardUserDefaults] valueForKey:FB_TOKEN]!=nil) {[self userLogin];}
else{
NSDictionary * dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:
FB_PROVIDER,
[[NSUserDefaults standardUserDefaults] valueForKey:FB_EMAIL],
[[NSUserDefaults standardUserDefaults] valueForKey:FB_PROVIDER_ID],
PUBLIC_KEY,
SECRET_KEY,
[[NSUserDefaults standardUserDefaults] valueForKey:FB_TOKEN],
[[NSUserDefaults standardUserDefaults] valueForKey:SESSION_TOKEN],
nil]
forKeys:[NSArray arrayWithObjects:#"name",#"email",#"provider_id", #"public_key", #"secret_key",#"token",#"session_token", nil]];
[webServiceController postRequestFromUrl:[NSString stringWithFormat:#"%#%#", ROOT_SERVER_URL, FB_SETTINGS_YES_URL] withDictionary:dict2];
}
}
What could be the error?. it always returns: FBSDKLog: An existing state change handler was assigned to the session and will be overwritten.
So I set up Applovin SDK in my app and Applovin ads only come up sparingly. All of my other apps with Applovin installed have the ads coming up accordingly. Anyone heard of this kind of error?
Here is what I have in the Appdelegate:
[ALSdk initializeSdk];
Chartboost *cb = [Chartboost sharedChartboost];
cb.appId = #"TAKEN OUT";
cb.appSignature = #"TAKEN OUT";
// Required for use of delegate methods. See "Advanced Topics" section below.
cb.delegate = self;
[cb startSession];
[cb cacheMoreApps];
[cb showInterstitial];
//AppLovin Interstitial Ad
if (self.theTimer == nil)
{
self.theTimer = [NSTimer scheduledTimerWithTimeInterval:1000 target:self selector:#selector(countdownTracker) userInfo:nil repeats:YES];//Repeat to yes
}
}
-(void)didCloseInterstitial:(NSString *)location
{
[ALInterstitialAd showOver:self.window];
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
if ([savedValue isEqualToString:#"yes"]) {
}
NSString *valueToSave = #"yes";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)stopTimer
{
if (self.theTimer != nil)
{
[self.theTimer invalidate];
self.theTimer = nil;
}
}
I am developing app using Estimote beacons, so i have three beacons one for Entry and second for Exit and third for messages.I want to fire push notification based on proximity user is getting so i get the push notification but issue is that it give multiple same notification.
so i use NSUserDefault to stop multiple pushnotification but it also not works so how can i stop this issue.i also check with local notification but it also give me multiple local notification.
Code:-
-(void)beaconManager:(ESTBeaconManager *)manager
didRangeBeacons:(NSArray *)beacons
inRegion:(ESTBeaconRegion *)region
{
if ([beacons count] == 0)
return;
ESTBeacon* beacon = [beacons firstObject];
int dist = [beacon.distance intValue];
if([region.identifier isEqualToString:BeaconIdentifier2]){
switch (beacon.proximity) {
case CLProximityUnknown:{
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Far"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Near"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Immediate"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[[NSUserDefaults standardUserDefaults] valueForKey:#"Unknown"] isEqualToString:#"FALSE"])
{
[[NSUserDefaults standardUserDefaults] setObject:#"TRUE" forKey:#"Unknown"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Call Unknown");
[self callPush];
}
}
break;
case CLProximityFar:{
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Unknown"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Near"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Immediate"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[[NSUserDefaults standardUserDefaults] valueForKey:#"Far"] isEqualToString:#"FALSE"])
{
[[NSUserDefaults standardUserDefaults] setObject:#"TRUE" forKey:#"Far"];
[[NSUserDefaults standardUserDefaults] synchronize];
//Call webservice
[self callPush];
}
}
break;
case CLProximityNear:{
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Unknown"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Far"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Immediate"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[[NSUserDefaults standardUserDefaults] valueForKey:#"Near"] isEqualToString: #"FALSE"])
{
[[NSUserDefaults standardUserDefaults] setObject:#"TRUE" forKey:#"Near"];
[[NSUserDefaults standardUserDefaults] synchronize];
//Call webservice
[self callPush];
}
}
break;
case CLProximityImmediate:{
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Unknown"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Far"];
[[NSUserDefaults standardUserDefaults] setObject:#"FALSE" forKey:#"Near"];
[[NSUserDefaults standardUserDefaults] synchronize];
if([[[NSUserDefaults standardUserDefaults] valueForKey:#"Immediate"] isEqualToString:#"FALSE"])
{
[[NSUserDefaults standardUserDefaults] setObject:#"TRUE" forKey:#"Immediate"];
[[NSUserDefaults standardUserDefaults] synchronize];
//Call webservice
[self callPush];
}
}
break;
}
}
}
Thanks in advance.
Try this,
BOOL isFar=TRUE;
- (void)locationManager:(CLLocationManager *)manager
didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
if (self.beaconRegion) {
if([beacons count] > 0)
{
//get closes beacon and find its major
CLBeacon *beacon = [beacons objectAtIndex:0];
switch (beacon.proximity)
{
case CLProximityUnknown:
break;
case CLProximityImmediate:
NSLog(#"Immediate");
if (isFar) {
isFar=false;
// Call WebService
}
break;
case CLProximityNear:
if (isFar) {
// Call WebService
}
isFar=false;
break;
case CLProximityFar:
NSLog(#"far");
if (!isFar) {
// call websercie
}
isFar=TRUE;
break;
default:
break;
}
}
}
}