需求
- 首次啟動廣告
- 熱啟動廣告(App進入后臺后,再次進入前臺)
- 熱啟動時間間隔控制 (App在后臺的時間)
- 每次運行期間廣告顯示次數(shù)控制 (單次運行期間允許顯示廣告次數(shù))
- 每天總的廣告顯示次數(shù)控制 (每天允許顯示廣告次數(shù))
- 區(qū)分熱啟動與App在前臺解鎖手機
App在前臺,用戶鎖屏相當(dāng)于進入后臺,解鎖后App進入前臺,都會執(zhí)行UIApplication對應(yīng)的代理方法。
一些App的非首次啟動廣告,解鎖后App在前臺的情況下也會顯示,比如微博。
一般廣告會有倒計時與跳過按鈕,這里只是一個簡易的效果,只有一張圖片:

ADShow.gif
實現(xiàn)與代碼封裝
設(shè)計
廣告的管理控制屬于一個單獨的邏輯模塊,可以單獨封裝一個類,以單例的形式存在。
相比直接將代碼寫在AppDelegate的各個代理方法中,這樣封裝可以更好的復(fù)用代碼,也能讓AppDelegate不至于太臃腫復(fù)雜。
解鎖判斷
對于解鎖狀態(tài)的判斷,已經(jīng)不能通過CFNotificationCenter的com.apple.springboard.lockstate等通知進行判斷了,否則可能在上傳App或者上架過程被拒。
可以在應(yīng)用即將進入前臺時,可以結(jié)合UIApplicationState和屏幕亮度來判斷:
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
CGFloat screenBrightness = [[UIScreen mainScreen] brightness];
BOOL isFromLockScreen = (state == UIApplicationStateInactive) ||
(state == UIApplicationStateBackground && screenBrightness <= 0.0);
統(tǒng)計控制
后臺時間和每次運行顯示的廣告次數(shù)可以用變量統(tǒng)計;每天的顯示次數(shù)則可以存入NSUserDefault。
封裝
只將一些控制選項暴露給外部:
@class KMADManager;
typedef BOOL(^ShowADFilter)(KMADManager *manager, BOOL isFirstLaunch, BOOL reachTimeThreshold, BOOL reachMaxSessionTime, BOOL reachMaxDailyTime);
typedef void(^ShowADAction)(KMADManager *manager, BOOL isFirstLaunch);
@interface KMADManager : NSObject
/// should exclude app active from screen unlock or not, default YES
@property (nonatomic, assign) BOOL excludeFromScreenLock;
/// time interval in seconds between background and foreground, default to 300s(5 minus)
@property (nonatomic, assign) NSTimeInterval timeThreshold;
/// current session AD show times
@property (nonatomic, assign, readonly) NSUInteger sessionShowTimes;
/// current daily AD show times
@property (nonatomic, assign, readonly) NSUInteger dailyShowTimes;
/// max time of showing AD per session(APP run one time), default to NSUIntegerMax
@property (nonatomic, assign) NSUInteger maxSessionShowTimes;
/// max time of showing AD per day, default to NSUIntegerMax
@property (nonatomic, assign) NSUInteger maxDailyShowTimes;
/// if exists, will use the return value of this block to determine should show a AD or not.
@property (nonatomic, copy) ShowADFilter showADFilter;
/// execute this block when an AD should be shown
@property (nonatomic, copy) ShowADAction showADAction;
+ (KMADManager *)sharedInstace;
@end
這樣外部在調(diào)用時,只需做簡單的設(shè)置和顯示廣告即可:
KMADManager *mag = [KMADManager sharedInstace];
mag.maxDailyShowTimes = 5;
mag.maxSessionShowTimes = 3;
mag.excludeFromScreenLock = NO;
mag.timeThreshold = 3 * 60; // 3 minus
mag.showADAction = ^(KMADManager *manager, BOOL isFirstLaunch) {
// here, code to show your AD
// e.g.
NSString *imageName = [NSString stringWithFormat:@"ad%@.jpg",@(manager.dailyShowTimes)];
UIImage *image = [UIImage imageNamed:imageName];
if (image) {
[ADHelper showADWithImage:image];
}
};
集成pod
上面的代碼已經(jīng)做成了pod
pod 'KMADManager', '~> 0.1.0'
如果還不知道怎么創(chuàng)建自己的pod,可以參考 CocoaPods創(chuàng)建自己的開源庫和私有庫
廣告顯示
可以單獨封裝一個類,里面使用UIWindow或者UIView來顯示廣告。