iOS开发两行代码添加启动页广告的功能

昨天在网上看了几篇关于集成启动页广告的博客,(参考自http://www.jianshu.com/p/ffa65292abf2)
发现添加到项目里面并不是那么方便(请原谅我说的方便是只需几行代码就集成一个功能的那种)。所以我参考了他们的代码,自己整合了一个只需两行代码添加广告的demo。(也许有很多不完善的地方,还望各路大神见谅)。

效果图:

66.gif

广告思路:第一次进入app时没有广告(因为广告的加载最好是从本地缓存获取,如果每次都从网络获取有可能因网速原因加载失败)。第一次启动的同时,根据后台返回的数据加载广告(一般是图片地址和广告链接),然后保存在本地。第二次启动的时候本地存在了广告,这个时候就可以显示了。然后请求最新的广告数据,如果和旧广告一样则不做操作;如果有新广告,则删除本地的旧广告,保存新广告,下次启动再显示。

下面上代码: ADView.h (继承自UIView)

#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;

/** 点击回调block */
@property (nonatomic,copy) void (^clickBlock)(NSString *url);

@end

@implementation ADView

-(NSUInteger)showTime
{
    if (_showTime == 0)
    {
        return 3;
    }
    else
    {
        return _showTime;
    }
}

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

/**
 *  初始化
 *
 *  @param frame    坐标
 *  @param imageUrl 图片地址
 *  @param adUrl    广告链接
 *  @param block    点击广告回调
 *
 *  @return self
 */
-(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];
        // 倒计时方法1:GCD
        // [self startCoundown];
        // 倒计时方法2:定时器
        [self startTimer];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
    }
    //不管本地是否存在广告图片都获取最新图片
    [self setNewADImgUrl:_imgUrl];
}

//判断沙盒中是否存在广告图片,如果存在,直接显示
- (BOOL)imageExist
{
    _filePath = [self getFilePathWithImageName:[UserDefaults valueForKey:adImageName]];
    BOOL isExist = [self isFileExistWithFilePath:_filePath];
    return isExist;
}

//跳转到广告页面
- (void)pushToAd{
    if (_clickAdUrl)
    {
        //把所点击的广告链接回调出去
        _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; //倒计时时间 + 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
{
    //获取图片名字(***.png)
    NSString *imgName = [[imgUrl componentsSeparatedByString:@"/"]lastObject];
    //拼接沙盒路径
    NSString *filePath = [self getFilePathWithImageName:imgName];
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (!isExist){// 如果本地没有该图片,下载新图片保存,并且删除旧图片
        [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];
        
        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) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    return nil;
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage
{
    NSString *imageName = [UserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}
@end

使用方法:在任何地方(当然是获取到广告数据的地方了)导入ADView.h,添加以下两行代码即可。

    //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
第一次提交自己的代码,还有很多待完善的地方,各位小伙伴如果用着觉得还可以,还请赏赐一个星星,谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,077评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,094评论 4 62
  • 关注孩子的心灵成长 前段时间,学堂有个孩子,总爱动手打人。熊校长听说后,叫我安排他做沙盘,并且一周必须做一次沙盘。...
    杨晓姝阅读 616评论 0 1
  • 我闭上眼睛,看到了眼前一片雪白,温润的白,环绕一周都是白的,上下间好似一体的。我好似看到了白色的会活动的物质,Ta...
    金金心阅读 330评论 1 1