BSoft&Co Humeurs et Rumeurs

14Feb/124

adsAutoSwitcher – Appcelerator Titanium script to rotate Admob and iAds on iOS applications

Ads-auto-switcher-for-Titanium

adsAutoSwitcher.js is a (commonJS) script that allow you to use both iAds and Admob at the same place within a ©Titanium iOS project. It works with ti.admob module(1.3) : With this script, per default, Admob is always shown, while iAds is shown (on top of admob) and hidden during some seconds.  I made it to simplify my life when i need to manage ads within my applications Wink The script manages to move and/or to resize an UI object when ads are visible. Be carefull with admob when closing a window. The module ti.admob is not really good to stop a refreshing admob..Thinking

adsAutoSwitcher.js is freely available on gitbub

[updated 2012/25/11] New major version !  adsAutoSwitcher V2. The updated V2 changelog is :

  • Rewrite and simplification for ads.js, renammed as adsAutoSwitcher
  • Compatible with Ti SDK > 2
  • commonJS archi
  • And really so much easier to use now!! Smile

How To use :

This adsAutoSwitcher prints the ads on top of a tableview object by moving it down The ads are delayed of 2sec
Before : tableview top = 0, height = 200
After : top = 50, height = 200

  1.  
  2. var myAds = require ('modules/adsAutoSwither');
  3. var ads = new myAds();
  4. ads.setAdmobPublisherId('myAdmobKey');
  5. ads.setIadsShowHide('iAdsShowHide.Window');
  6. ads.setGlobalDelayStart(2000);
  7. ads.showAdvert(tableView,'move','top');

Same as before, but now, the tableview is resized from its top
Before : tableview top = 0, height = 200
After : top = 50, height = 150

  1. [...]
  2. ads.showAdvert(tableView,'resize','top');

Same as before, but now, the tableview is resized from its bottom
Before : tableview top = 0, height = 200.
After : top = 0, height = 150, so bottom is now 150

  1. [...]
  2. ads.showAdvert(tableView,'resize','bottom');

Fixed banner at top = 120. No UI object resized or moved

  1. [...]
  2. ads.setAdsTopInit(120);
  3. ads.showAdvert(tableView,'','');

Full script for adsAutoSwitcher.js 2.0.008

  1.  
  2. Titanium.Admob = Ti.Admob;
  3.  
  4. function AdsAutoSwither() {
  5.     /**
  6.      *  Single contexte name of window
  7.      *  Only use it if your application is a single context application. Then set here the instance of your window
  8.      */
  9.     var _singleContextWin = null;
  10.     this.setSingleContextWin = function(name) {
  11.         _singleContextWin = name;    
  12.     };
  13.  
  14.     /**
  15.      *  Delay in ms before calling the ads
  16.      */
  17.     var _globalDelayStart = 0;
  18.     this.setGlobalDelayStart = function(ms) {
  19.         _globalDelayStart = ms;    
  20.     };
  21.  
  22.     /**
  23.      *  Top margin (px) for the object to move
  24.      */
  25.     var _objMargin = 0;
  26.     this.setObjMargin = function(px){
  27.         _objMargin = px;    
  28.     };
  29.  
  30.     /**
  31.      *  To enabled or not admob. Don't forget to change ads.iadsStartDelay if no admob
  32.      */
  33.     var _useAdmob = true;
  34.     this.setUseAdmob = function(b) {
  35.         _useAdmob = b;    
  36.     };
  37.  
  38.     /**
  39.      *  To enabled or not iAds.
  40.      */
  41.     var _useIads = true;  
  42.     this.setUseIads = function(b) {
  43.         _useIads = b;
  44.     };
  45.  
  46.     /**
  47.      *  Milliseconds before starting iads
  48.      */
  49.     var _iadsStartDelay = 30000;
  50.     this.setIadsStartDelay = function(ms) {
  51.         _iadsStartDelay = ms;        
  52.     };
  53.  
  54.     /**
  55.      *  Initial top position for the ads banners
  56.      *  Set it to Ti.Platform.displayCaps.platformHeight + 50 for a bottom ad
  57.      */
  58.     var _adsTopInit = -50;
  59.     this.setAdsTopInit = function(px) {
  60.         _adsTopInit = px;    
  61.     };
  62.  
  63.     /**
  64.      *  The event's name to be fired. It's recommanded to use one per ads's instance.
  65.      */
  66.     var _iAdsShowHide = 'iAdsShowHide';
  67.     this.setIadsShowHide = function(str) {
  68.         _iAdsShowHide = str;
  69.     };
  70.  
  71.     /**
  72.      *  Required : your admob id
  73.      */
  74.     var _admobPublisherId = null;
  75.     this.setAdmobPublisherId = function(str) {
  76.         _admobPublisherId = str;    
  77.     };
  78.  
  79.     // -- Admob extra public parameters -- //
  80.     /**
  81.      *  Date of birth, to better target the ads, new Date(1985, 10, 1, 12, 1, 1)
  82.      */
  83.     this.adDateOfBirth = '';
  84.  
  85.     /**
  86.      *  Gender 'male' or 'female'
  87.      */
  88.     this.adGender  = '';
  89.  
  90.     /**
  91.      *  Keywords about the ads to print
  92.      */
  93.     this.adKeywords = '';
  94.  
  95.     /**
  96.      *  Test mode for admob
  97.      */
  98.     this.adTesting = false;
  99.  
  100.     /**
  101.      *  admob's backgroundColor
  102.      */
  103.     this.adBackgroundColor =  "#FDFEFD";
  104.  
  105.     // --   iAds extra public parameters     -- //
  106.     /**
  107.      *  iAds's border color
  108.      */
  109.     this.iAdsBorderColor = '#FDFEFD';
  110.  
  111.     /**
  112.      *  iAds's backgroundColor
  113.      */
  114.     this.iAdsBackgroundColor = '#FDFEFD';
  115.  
  116.     /**
  117.      *  How long iAd stay visible (milliseconds)
  118.      */
  119.     this.iAdsTimeToShow = 15000;
  120.  
  121.     /**
  122.      *  How long iAd is hidden (milliseconds)
  123.      */
  124.     this.iAdsTimeToHide = 30000;
  125.  
  126.     /**
  127.      *  Public methods to expose the actual iAds/Admob visibility
  128.      */
  129.     var _iAdsVisible = false;
  130.     this.getIadsVisible = function() {
  131.         return _iAdsVisible;    
  132.     };
  133.     var _adMobVisible = false;
  134.     this.getAdMobVisible = function() {
  135.         return _adMobVisible;    
  136.     };
  137.  
  138.     // --   Private members     -- //
  139.     /**
  140.      *  The UI object to be moved/resized when an ad is visible
  141.      */
  142.     var _objUI = {};
  143.  
  144.     /**
  145.      *  The type of transformation for the object, can be : 'move' or 'resize' or '' (empty for fixed banner)
  146.      */
  147.     var _alterFrom = '';
  148.  
  149.     /**
  150.      *  From where the object transformation should start : 'top' or 'bottom'
  151.      */
  152.     var _alterType = '';
  153.  
  154.     /**
  155.      *  Top, bottom and height for the objUI
  156.      */
  157.     var _objUIinitTop, _objUIinitBottom, _objUIinitHeight;
  158.  
  159.     var _admob = null;
  160. // ----------------------------------------------------------------------------
  161.  
  162. // ----------------------------------------------------------------------------
  163. // ----------------------------------------------------------------------------
  164.     var _hideExtraAdsSpace = function() {
  165.         if (_alterType === 'move') {
  166.             if (_alterFrom === 'top') {
  167.                 _objUI.animate({top:_objUIinitTop+ _objMargin,duration:250});
  168.             }    
  169.             else { // TO CHECK ( - adsmargin?)
  170.                 _objUI.animate({bottom:_objUIinitBottom+ _objMargin,duration:250});
  171.             }    
  172.         } else {
  173.             if (_alterFrom === 'top') {
  174.                 _objUI.animate({height:_objUIinitHeight,top:_objUIinitTop,duration:250});
  175.             }
  176.             else {
  177.                 _objUI.animate({height:_objUIinitHeight,bottom:_objUIinitBottom,duration:250});
  178.             }    
  179.         }    
  180.     };
  181. // ----------------------------------------------------------------------------
  182.  
  183. // ----------------------------------------------------------------------------
  184.     var _buildIads = function() {
  185.         var firstRun = true;
  186.         if (parseFloat(Titanium.Platform.version) >= 3.2) {
  187.             Ti.API.info('ads.showiAds - build iads');
  188.             var _iads = Ti.UI.iOS.createAdView({
  189.                 width: Ti.UI.SIZE || 'auto',
  190.                 height: Ti.UI.SIZE || 'auto',
  191.                 top: _adsTopInit,  
  192.                 borderColor: this.iAdsBorderColor,
  193.                 backgroundColor: this.iAdsBackgroundColor
  194.             });
  195.             _iads.addEventListener('load', function(){
  196.                 Ti.API.info("ads.showiAds - iads loaded. First Run ? :"+firstRun);
  197.                 _iAdsVisible = true;
  198.                 if (firstRun) {
  199.                     Ti.API.info("ads.showiAds - First iAds run : True");
  200.                     firstRun = false;
  201.                 }
  202.                 else {
  203.                     Ti.API.info("ads.showiAds - First iAds run ? : False");
  204.                 }
  205.                 timer=setInterval(_showIads, this.iAdsTimeToShow);
  206.             });
  207.             _iads.addEventListener('error', function(e){
  208.                 Ti.API.info("ads.showiAds - iads error :"+e.message+ " --- adMobVisible="+_adMobVisible);
  209.                 if (_iAdsVisible &&  _alterType != '') {
  210.                     if (_adMobVisible) {
  211.                         if (_alterType === 'move') {
  212.                             if (_alterFrom === 'top') {
  213.                                 _objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
  214.                             }    
  215.                             else { // TO CHECK ( - adsmargin?)
  216.                                 _objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
  217.                             }    
  218.                         } else {
  219.                             if (_alterFrom === 'top') {
  220.                                 _objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
  221.                             }
  222.                             else {
  223.                                 _objUI.animate({height:_objUIinitHeight-50,bottom:_objUIinitBottom-53,duration:250});
  224.                             }    
  225.                         }
  226.  
  227.                     } else { // hide the extra space for ads
  228.                         _hideExtraAdsSpace();
  229.                     }
  230.                 }
  231.                 _iads.top = _adsTopInit;
  232.                 _iAdsVisible = false;
  233.             });
  234.             try {
  235.                 Titanium.UI.currentWindow.add(_iads);
  236.             }
  237.             catch (e) {
  238.                 _singleContextWin.add(_iads);
  239.             }
  240.         }
  241.     };
  242. // ----------------------------------------------------------------------------
  243.  
  244. // ----------------------------------------------------------------------------
  245.     var _showIads = function() {
  246.         Ti.API.info("ads.showiAds - Receive iAdsShowHide. ads.iAdsVisible :"+_iAdsVisible + " -- iads.visible: "+_iads.visible+ " -- ads.adMobVisible: "+_adMobVisible);
  247.         if (_iAdsVisible && _iads.visible) {
  248.             if (_adMobVisible === false) {
  249.                 // if admob's not visible, let iAds on screen
  250.             }
  251.             else { // to hide iAds
  252.                 _iads.animate({top:_adsTopInit, duration:500}, function() { _iads.hide(); Ti.API.info("ads.showiAds - hide iads"); });
  253.             }
  254.         }  
  255.         else { // to show iAds
  256.             if (_adMobVisible === false && _alterType != '') {
  257.                 if (_alterType === 'move') {
  258.                     if (_alterFrom === 'top') {
  259.                         _objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
  260.                     }    
  261.                     else { // TO CHECK ( - adsmargin?)
  262.                         _objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
  263.                     }    
  264.                 } else {
  265.                     if (_alterFrom === 'top') {
  266.                         _objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
  267.                     }
  268.                     else {
  269.                         _objUI.animate({height:_objUIinitHeight-58,bottom:_objUIinitBottom-58,duration:250});
  270.                     }    
  271.                 }
  272.             }
  273.             _iads.show();
  274.             Ti.API.info("ads.showiAds - iads show");
  275.             if (_alterFrom === 'top') {
  276.                 _iads.animate({top:_objUIinitTop,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
  277.             } else if (_alterFrom === 'bottom') {
  278.                 _iads.animate({top:_objUIinitBottom-54,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
  279.             }    
  280.         }
  281.     };    
  282. // ----------------------------------------------------------------------------
  283.  
  284. // ----------------------------------------------------------------------------
  285.     var _buildAdmob = function() {
  286.         if (_admob === null) {
  287.             Ti.API.info("ads.buildAdmob - try buildAdmob - ");
  288.             _admob = Ti.Admob.createView({        
  289.                 publisherId: _admobPublisherId, // required  
  290.                 top: _adsTopInit,
  291.                 left: 0,
  292.                 width: Ti.Platform.displayCaps.getPlatformWidth(), //320, // required
  293.                 height: 50, // required
  294.                 testing: this.adTesting,
  295.                 adBackgroundColor: this.adBackgroundColor,
  296.                 dateOfBirth: this.adDateOfBirth, //new Date(1985, 10, 1, 12, 1, 1),
  297.                 gender: this.adGender, //'male',
  298.                 keywords: this.adKeywords, //'',
  299.                 refreshAd:15.0 //not working with actual ti.admob module (1.3), set refresh time within admob site
  300.             });
  301.             _admob.addEventListener('didFailToReceiveAd', function() {
  302.                 _admob.top = _adsTopInit;
  303.                 _admob = null;
  304.                 if (!_iAdsVisible && _alterType != '') {
  305.                     _hideExtraAdsSpace();
  306.                 }
  307.                 _adMobVisible = false;
  308.                 setTimeout(_buildAdmob, 10000);
  309.                 Ti.API.info("ads.buildAdmob - admob error : didFailToReceiveAd. Retry in 10s. adMobVisible:"+_adMobVisible);
  310.             });
  311.             _admob.addEventListener('didReceiveAd', function() {
  312.                 Ti.API.info("ads.buildAdmob - admob event : didReceiveAd");
  313.                 _showAdmob();
  314.             });
  315.             try {
  316.                 Titanium.UI.currentWindow.add(_admob);
  317.             }
  318.             catch (e) {
  319.                 _singleContextWin.add(_admob);
  320.             }
  321.         }
  322.     };
  323. // ----------------------------------------------------------------------------
  324.  
  325. // ----------------------------------------------------------------------------
  326.     var _showAdmob = function() {
  327.         if (_adMobVisible === false) {
  328.             try {
  329.                 if (!_iAdsVisible && _alterType != '') {
  330.                     if (_alterType === 'move') {
  331.                         if (_alterFrom === 'top') {
  332.                             _objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
  333.                         }    
  334.                         else { // TO CHECK ( - adsmargin?)
  335.                             _objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
  336.                         }    
  337.                     } else {
  338.                         if (_alterFrom === 'top') {
  339.                             _objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
  340.                         }
  341.                         else {
  342.                             _objUI.animate({height:_objUIinitHeight-58,bottom:_objUIinitBottom-58,duration:250});
  343.                         }    
  344.                     }
  345.                 }
  346.                 _adMobVisible = true;
  347.                 if (_alterFrom === 'top') {
  348.                     _admob.animate({top:_objUIinitTop,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
  349.                 } else if (_alterFrom === 'bottom') {
  350.                     _admob.animate({top:_objUIinitBottom-58,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
  351.                 }
  352.             }
  353.             catch (e) {
  354.                 _adMobVisible = false;
  355.                 Ti.API.info("ads.showAdmob - catch admob error showAdmob");
  356.                 setTimeout(_buildAdmob, 10000);
  357.             }
  358.         }
  359.     };
  360. // ----------------------------------------------------------------------------
  361.  
  362. // ----------------------------------------------------------------------------
  363.     /**
  364.      *  showAdvert  : the unique function to call to start showing the ads
  365.      *  objUI       : the object to move or resize.  
  366.      *  alterType   : The type of transformation for the object, can be : 'move' or 'resize' or '' (empty for a fixed banner)
  367.      *  alterFrom   : From where the object transformation should start : 'top' or 'bottom' of the objUI
  368.      */
  369.     this.showAdvert = function(objUI,alterType,alterFrom) {
  370.         if (Titanium.Network.online) {
  371.             _objUI = objUI;
  372.             _alterFrom = alterFrom;
  373.             _alterType = alterType;
  374.  
  375.             var postLayoutCallback  = function(e,AdsAutoSwither) {
  376.                 _objUI.removeEventListener('postlayout', postLayoutCallback);
  377.                 _objUIinitTop = objUI.getTop(), _objUIinitBottom = objUI.rect.bottom, _objUIinitHeight = objUI.rect.height;
  378.                 if (_objUIinitTop == 'undefined') {
  379. //                    _objUIinitTop = _objUIinitBottom - _objUIinitHeight - 50;
  380.                 }
  381.                 Ti.API.info('_objUIinitTop :'+_objUIinitTop+' -- _objUIinitBottom :'+_objUIinitBottom+' -- _objUIinitHeight :'+_objUIinitHeight);
  382.                 setTimeout(function(){
  383.                     if (_useAdmob) {
  384.                         Ti.Admob = require('ti.admob');
  385.                         _buildAdmob();
  386.                     }
  387.                     if (_useIads) { setTimeout(_buildIads, _iadsStartDelay); }  
  388.                 },_globalDelayStart)
  389.             }
  390.             _objUI.addEventListener('postlayout', postLayoutCallback);
  391.         }
  392.         else { // No internet connection. Retry in 30sec
  393.             setTimeout(this.showAdvert, 30000);  
  394.         }
  395.     };
  396. }
  397. module.exports = AdsAutoSwither;

adsAutoSwitcher.js is freely available on gitbub

Comments (4) Trackbacks (0)
  1. Hi Dave,
    sorry for the delay.. i saw your comment, but forgot itThinking
    Well i don’t know what to say about your problem.
    I guess I need more information to help you.
    I’m using my script with tableview too, and have no pb. (Look at iAdditifs or myQRCode on the AppStore).

  2. Hey. Thanks for posting this script. I’m hoping to get it working. I am getting a WARNING when I test it however.

    “Invalid dimension value (nan) requested. Making the dimension undefined instead.”

    Here is my code:

    var myAds = require (‘adsAutoSwither’);
    var ads = new myAds();
    ads.setAdmobPublisherId(‘a1511dcf5c9a343′);
    ads.setIadsShowHide(‘iAdsShowHide.Window’);
    ads.setGlobalDelayStart(2000);
    ads.showAdvert(searchTable,’resize’,’top’);

    Im finding its moving the table down about 25px vs 50 with an empty gap above and below (centered in window) Any help is appreciated. Thanks

  3. Hi,

    to put the ads at the bottom of the screen, simply init the object with those values :
    ads.iadsTopInit = 490; // to hide the ads below the bottom
    ads.admobTopInit = 490;
    ads.topPos = 430; // to show the ads at the bottom (430px + 50px of the ads = 480)

    bsoft

  4. HI , How do I gt an add to sit at the bottom of the screen rather than the top


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette

Trackbacks are disabled.