您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

啟動廣告怎麼做才不閃退:本地快取策略與完整 ADView 實作

編輯:iOS 開發基礎

先想清楚策略

啟動廣告最容易犯的錯,是每次啟動都從網路抓圖。網路不穩時廣告會加载失敗,畫面一塊空白。正確的做法是「本機優先、後台異步更新」:

  1. 第一次進入 App 不顯示廣告,同時向後端請求廣告資料(通常是圖片網址與跳轉鏈接),下載後存在本機。
  2. 第二次啟動時,本機已有快取,直接顯示。
  3. 顯示的同時再請求一次最新廣告:若與現有的一樣就什麼都不做;若有新版,則刪除舊圖、保存新圖,下次啟動才會生效。

這樣使用者永遠不會看到白屏,廣告更新也只是「落後一次啟動」而已,完全可以接受。

ADView.h

#import <UIKit/UIKit.h>

#define ScreenWidth  [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define UserDefaults [NSUserDefaults standardUserDefaults]

static NSString *const adImageName = @"adImageName";
static NSString *const adUrl       = @"adUrl";

@interface ADView : UIView

/** 倒計時(預設 3 秒) */
@property (nonatomic, assign) NSUInteger showTime;

/** 初始化方法 */
- (instancetype)initWithFrame:(CGRect)frame
                     andImgUrl:(NSString *)imageUrl
                      andADUrl:(NSString *)adUrl
                 andClickBlock:(void (^)(NSString *clikImgUrl))block;

/** 顯示廣告頁 */
- (void)show;

@end

ADView.m

#import "ADView.h"

@interface ADView ()

@property (nonatomic, strong) UIImageView *adView;
@property (nonatomic, strong) UIButton    *countBtn;
@property (nonatomic, strong) NSTimer     *countTimer;
@property (nonatomic, assign) NSUInteger   count;

/** 廣告圖片本地路徑 */
@property (nonatomic, copy) NSString *filePath;
/** 新廣告圖片地址 */
@property (nonatomic, copy) NSString *imgUrl;
/** 新廣告的鏈接 */
@property (nonatomic, copy) NSString *adUrl;
/** 當前展示的廣告鏈接 */
@property (nonatomic, copy) NSString *clickAdUrl;
/** 點擊回調 */
@property (nonatomic, copy) void (^clickBlock)(NSString *url);

@end

@implementation ADView

- (NSUInteger)showTime {
    return (_showTime == 0) ? 3 : _showTime;
}

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

- (instancetype)initWithFrame:(CGRect)frame
                    andImgUrl:(NSString *)imageUrl
                     andADUrl:(NSString *)adUrl
                andClickBlock:(void (^)(NSString *))block {
    self = [super initWithFrame:frame];
    if (self) {
        _clickBlock = block;
        _imgUrl = imageUrl;
        _adUrl  = adUrl;

        // 廣告圖片
        _adView = [[UIImageView alloc] initWithFrame:frame];
        _adView.userInteractionEnabled = YES;
        _adView.contentMode = UIViewContentModeScaleAspectFill;
        _adView.clipsToBounds = YES;

        UITapGestureRecognizer *tap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];
        [_adView addGestureRecognizer:tap];

        // 跳過按鈕
        CGFloat btnW = 60;
        CGFloat btnH = 30;
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - btnW - 24, btnH, btnW, btnH)];
        [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        _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)show {
    // 本地有快取才顯示
    if ([self imageExist]) {
        [_countBtn setTitle:[NSString stringWithFormat:@"跳過%zd", self.showTime]
                   forState:UIControlStateNormal];

        _adView.image = [UIImage imageWithContentsOfFile:_filePath];
        _clickAdUrl = [UserDefaults valueForKey:adUrl];

        // 倒計時方案一:GCD
        // [self startCoundown];
        // 倒計時方案二:計時器
        [self startTimer];

        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
    }

    // 無論本地有沒有廣告,都去抓一次最新的
    [self setNewADImgUrl:_imgUrl];
}

// 判斷沙盒中是否存在廣告圖片
- (BOOL)imageExist {
    _filePath = [self getFilePathWithImageName:[UserDefaults valueForKey:adImageName]];
    return [self isFileExistWithFilePath:_filePath];
}

// 跳轉廣告頁
- (void)pushToAd {
    if (_clickAdUrl) {
        if (_clickBlock) {
            _clickBlock(_clickAdUrl);
        }
        [self dismiss];
    }
}

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

// 計時器倒計時
- (void)startTimer {
    _count = self.showTime;
    [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

// GCD 倒計時
- (void)startCoundown {
    __block NSUInteger timeout = self.showTime + 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);

    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dismiss];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_countBtn setTitle:[NSString stringWithFormat:@"跳過%zd", timeout]
                           forState:UIControlStateNormal];
            });
            timeout--;
        }
    });

    dispatch_resume(_timer);
}

// 移除廣告頁
- (void)dismiss {
    [self.countTimer invalidate];
    self.countTimer = nil;

    [UIView animateWithDuration:0.3f animations:^{
        self.alpha = 0.f;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

// 檢查並更新廣告
- (void)setNewADImgUrl:(NSString *)imgUrl {
    NSString *imgName = [[imgUrl componentsSeparatedByString:@"/"] lastObject];
    NSString *filePath = [self getFilePathWithImageName:imgName];

    if (![self isFileExistWithFilePath:filePath]) {
        [self downloadAdImageWithUrl:imgUrl imageName:imgName];
    }
}

/** 下載新圖片(實務上也可以直接用 SDWebImage) */
- (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];
        if (!image) { return; }

        NSString *filePath = [self getFilePathWithImageName:imageName];

        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {
            NSLog(@"保存成功");
            [self deleteOldImage];
            [UserDefaults setValue:imageName forKey:adImageName];
            [UserDefaults setValue:_adUrl forKey:adUrl];
            [UserDefaults synchronize];
        } else {
            NSLog(@"保存失敗");
        }
    });
}

#pragma mark - 檔案操作

- (BOOL)isFileExistWithFilePath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

- (NSString *)getFilePathWithImageName:(NSString *)imageName {
    if (!imageName) { return nil; }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
}

- (void)deleteOldImage {
    NSString *imageName = [UserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
}

@end

呼叫方式

NSString *imageUrl = @"https://img5q.duitang.com/uploads/item/201505/25/20150525223238_NdQrh.thumb.700_0.png";
NSString *adURL = @"https://tieba.baidu.com/";

// 1. 建立廣告
ADView *adView = [[ADView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds
                                      andImgUrl:imageUrl
                                       andADUrl:adURL
                                  andClickBlock:^(NSString *clikImgUrl) {
                                      NSLog(@"進入廣告: %@", clikImgUrl);
                                  }];

// 2. 顯示廣告
[adView show];

Github 地址:https://github.com/xiongoahc/LaunchAD

仔 review 這份程式碼時有幾個可以再加強的地方:圖片下載建議加上超時與失敗重試;NSUserDefaults 不適合放大數據,這裡只存檔名是對的;另外,若廣告需要曝光/點擊統計,記得在 show 與 pushToAd 這兩個時機各補上一個回報。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved