iOS-APP啟動(dòng)頁(yè)加載廣告

目前市場(chǎng)上很多APP(如淘寶、美團(tuán)、微博、UC)在啟動(dòng)圖加載完畢后,還會(huì)顯示幾秒的廣告,右上角都有個(gè)跳過(guò)按鈕可以選擇立即跳過(guò)這個(gè)廣告,有的APP在點(diǎn)擊廣告頁(yè)之后還會(huì)進(jìn)入一個(gè)廣告頁(yè)。
他們玩的樂(lè)此不疲,產(chǎn)品汪們見(jiàn)了自然也是不會(huì)放過(guò)這個(gè)效果:


思路如下:

  1. 封裝廣告頁(yè), 展現(xiàn)跳過(guò)按鈕實(shí)現(xiàn)倒計(jì)時(shí)功能
    2.判斷廣告頁(yè)面是否更新。異步下載新圖片, 刪除老圖片
    3.廣告頁(yè)顯示
    4.廣告頁(yè)點(diǎn)擊后展示頁(yè)

廢話(huà)少說(shuō),這邊先上核心代碼了:

一. 封裝廣告頁(yè), 展現(xiàn)跳過(guò)按鈕實(shí)現(xiàn)倒計(jì)時(shí)功能

ZLAdvertView.h: 先封裝出來(lái)廣告頁(yè),露出顯示廣告頁(yè)面方法和圖片路徑

#import <UIKit/UIKit.h>

#define kscreenWidth [UIScreen mainScreen].bounds.size.width
#define kscreenHeight [UIScreen mainScreen].bounds.size.height
#define kUserDefaults [NSUserDefaults standardUserDefaults]
static NSString *const adImageName = @"adImageName";
static NSString *const adUrl = @"adUrl";

@interface ZLAdvertView : UIView

/**
*  顯示廣告頁(yè)面方法
*/
- (void)show;

/**
 *  圖片路徑
 */
@property (nonatomic, copy) NSString *filePath;

@end

ZLAdvertView.m:

核心代碼見(jiàn)下面代碼塊:

#import "ZLAdvertView.h"

@interface ZLAdvertView ()

@property (nonatomic, strong) UIImageView *adView;

@property (nonatomic, strong) UIButton *countBtn;

@property (nonatomic, strong) NSTimer *countTimer;

@property (nonatomic, assign) int count;

@end

// 廣告顯示的時(shí)間
static int const showtime = 3;

1. 為廣告頁(yè)面添加一個(gè)點(diǎn)擊手勢(shì),跳轉(zhuǎn)到廣告頁(yè)面.

@implementation ZLAdvertView

- (NSTimer *)countTimer {
    
    if (!_countTimer) {
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    return _countTimer;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        // 1.廣告圖片
        _adView = [[UIImageView alloc] initWithFrame:frame];
        _adView.userInteractionEnabled = YES;
        _adView.contentMode = UIViewContentModeScaleAspectFill;
        _adView.clipsToBounds = YES;
        // 為廣告頁(yè)面添加一個(gè)點(diǎn)擊手勢(shì),跳轉(zhuǎn)到廣告頁(yè)面
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];
        [_adView addGestureRecognizer:tap];
        
        // 2.跳過(guò)按鈕
        CGFloat btnW = 60;
        CGFloat btnH = 30;
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(kscreenWidth - btnW - 24, btnH, btnW, btnH)];
        [_countBtn addTarget:self action:@selector(removeAdvertView) forControlEvents:UIControlEventTouchUpInside];
        [_countBtn setTitle:[NSString stringWithFormat:@"跳過(guò)%d", showtime] forState:UIControlStateNormal];
        _countBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_countBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _countBtn.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
        _countBtn.layer.cornerRadius = 4;
        
        [self addSubview:_adView];
        [self addSubview:_countBtn];
        
    }
    return self;
}

- (void)setFilePath:(NSString *)filePath {
    
    _filePath = filePath;
    _adView.image = [UIImage imageWithContentsOfFile:filePath];
}

- (void)pushToAd {
    
    [self removeAdvertView];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLPushToAdvert" object:nil userInfo:nil];
}

2. 廣告頁(yè)面的跳過(guò)按鈕倒計(jì)時(shí)功能可以通過(guò)定時(shí)器或者GCD實(shí)現(xiàn)(這里以廣告倒計(jì)時(shí)3s 做例子)

- (void)countDown {
    
    _count --;
    [_countBtn setTitle:[NSString stringWithFormat:@"跳過(guò)%d",_count] forState:UIControlStateNormal];
    if (_count == 0) {
        
        [self removeAdvertView];
    }
}

// 廣告頁(yè)面的跳過(guò)按鈕倒計(jì)時(shí)功能可以通過(guò)定時(shí)器或者GCD實(shí)現(xiàn)
- (void)show {
    
    // 倒計(jì)時(shí)方法1:GCD
//    [self startCoundown];
    
    // 倒計(jì)時(shí)方法2:定時(shí)器
    [self startTimer];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
}

// 定時(shí)器倒計(jì)時(shí)
- (void)startTimer {
    
    _count = showtime;
    [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

// GCD倒計(jì)時(shí)
- (void)startCoundown {
    
    __weak __typeof(self) weakSelf = self;
    __block int timeout = showtime + 1; //倒計(jì)時(shí)時(shí)間 + 1
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒執(zhí)行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒計(jì)時(shí)結(jié)束,關(guān)閉
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf removeAdvertView];
                
            });
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [_countBtn setTitle:[NSString stringWithFormat:@"跳過(guò)%d",timeout] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

// 移除廣告頁(yè)面
- (void)removeAdvertView {
    
    // 停掉定時(shí)器
    [self.countTimer invalidate];
    self.countTimer = nil;
    
    [UIView animateWithDuration:0.3f animations:^{
        
        self.alpha = 0.f;
        
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
    
}

@end

二. 判斷廣告頁(yè)面是否更新。異步下載新圖片, 刪除老圖片

因?yàn)閺V告頁(yè)的內(nèi)容要實(shí)時(shí)顯示,在無(wú)網(wǎng)絡(luò)狀態(tài)或者網(wǎng)速緩慢的情況下不能延遲加載,或者等到首頁(yè)出現(xiàn)了再加載廣告頁(yè)。所以這里不采用網(wǎng)絡(luò)請(qǐng)求廣告接口去獲取圖片地址然后加載圖片的方式,而是先將圖片異步下載到本地,并保存圖片名,每次打開(kāi)app時(shí)先根據(jù)本地存儲(chǔ)的圖片名查找沙盒中是否存在該圖片,如果存在,則顯示廣告頁(yè)。
在AppDelegate.m 里:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]];
    [self.window makeKeyAndVisible];
    
    // 設(shè)置啟動(dòng)頁(yè)廣告
    [self setupAdvert];
    
    return YES;
}

1.判斷沙盒中是否存在廣告圖片,如果存在,直接顯示

/**
 *  設(shè)置啟動(dòng)頁(yè)廣告
 */
- (void)setupAdvert {
    
    // 1.判斷沙盒中是否存在廣告圖片,如果存在,直接顯示
    NSString *filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) { // 圖片存在
        
        ZLAdvertView *advertView = [[ZLAdvertView alloc] initWithFrame:self.window.bounds];
        advertView.filePath = filePath;
        [advertView show];
    }
    
    // 2.無(wú)論沙盒中是否存在廣告圖片,都需要重新調(diào)用廣告接口,判斷廣告是否更新
    [self getAdvertisingImage];
}

/**
 *  判斷文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

2.無(wú)論沙盒中是否存在廣告圖片,都需要重新調(diào)用獲取廣告接口,判斷廣告是否更新

/**
 *  初始化廣告頁(yè)面
 */
- (void)getAdvertisingImage {
    
    // TODO 請(qǐng)求廣告接口
    // 這里原本應(yīng)該采用廣告接口,現(xiàn)在用一些固定的網(wǎng)絡(luò)圖片url代替
    NSArray *imageArray = @[
                            @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
                            @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
                            @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
                            ];
    NSString *imageUrl = imageArray[arc4random() % imageArray.count];
    
    // 獲取圖片名:43-130P5122Z60-50.jpg
    NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
    NSString *imageName = stringArr.lastObject;
    
    // 拼接沙盒路徑
    NSString *filePath = [self getFilePathWithImageName:imageName];
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (!isExist){ // 如果該圖片不存在,則刪除老圖片,下載新圖片
        
        [self downloadAdImageWithUrl:imageUrl imageName:imageName];
    }
}

3.異步下載新圖片, 刪除老圖片

/**
 *  下載新圖片
 */
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名稱(chēng)
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [kUserDefaults setValue:imageName forKey:adImageName];
            [kUserDefaults synchronize];
            // 如果有廣告鏈接,將廣告鏈接也保存下來(lái)
        }else{
            NSLog(@"保存失敗");
        }
        
    });
}

/**
 *  刪除舊圖片
 */
- (void)deleteOldImage {
    
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  根據(jù)圖片名拼接文件路徑
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName {
    
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}

三. 廣告頁(yè)顯示。

廣告頁(yè)的顯示代碼可以放在AppDeleate中,也可以放在首頁(yè)的控制器中。如果代碼是在AppDelegate中,可以通過(guò)發(fā)送通知的方式,讓首頁(yè)push到廣告詳情頁(yè).

首頁(yè)控制器HomeViewController.m:

#import "HomeViewController.h"
#import "ZLAdvertViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"首頁(yè)";
    
    self.view.backgroundColor = [UIColor greenColor];
    
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToAd) name:@"ZLPushToAdvert" object:nil];
}

// 進(jìn)入廣告鏈接頁(yè)
- (void)pushToAd {
    
    ZLAdvertViewController *adVc = [[ZLAdvertViewController alloc] init];
    [self.navigationController pushViewController:adVc animated:YES];
    
}
@end

四. 廣告頁(yè)點(diǎn)擊后展示頁(yè)。

如果點(diǎn)擊廣告需要跳轉(zhuǎn)廣告詳情頁(yè)面,那么廣告鏈接地址也需要用NSUserDefaults存儲(chǔ)。注意:廣告詳情頁(yè)面是從首頁(yè)push進(jìn)去的
廣告鏈接頁(yè)ZLAdvertViewController.h :

//  廣告鏈接頁(yè)
#import <UIKit/UIKit.h>

@interface ZLAdvertViewController : UIViewController

@property (nonatomic, copy) NSString *adUrl;

@end

ZLAdvertViewController.m :

#import "ZLAdvertViewController.h"

@interface ZLAdvertViewController ()

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation ZLAdvertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"點(diǎn)擊進(jìn)入廣告鏈接";
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.backgroundColor = [UIColor whiteColor];
    
    if (!self.adUrl) {
        self.adUrl = @"http://www.baidu.com";
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.adUrl]];
    [_webView loadRequest:request];
    [self.view addSubview:_webView];
}

- (void)setAdUrl:(NSString *)adUrl {
    _adUrl = adUrl;
}
@end

注意:
廣告頁(yè)面的底部和啟動(dòng)圖的底部一般都是相同的,給用戶(hù)的錯(cuò)覺(jué)就是啟動(dòng)圖加載完之后把廣告圖放在了啟動(dòng)圖上,而且不能有偏差。所以我們開(kāi)發(fā)要圖時(shí)需要提醒美工在制作廣告圖的時(shí)候要注意下。

啟動(dòng)頁(yè)進(jìn)入廣告.gif
啟動(dòng)頁(yè)跳過(guò)廣告.gif

如果需要啟動(dòng)動(dòng)態(tài)頁(yè)跳過(guò)的這種啟動(dòng)頁(yè)方案 ,請(qǐng)移步: iOS-啟動(dòng)動(dòng)態(tài)頁(yè)跳過(guò)設(shè)計(jì)思路

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容