您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页app三秒启动广告与缓存

app三秒启动广告与缓存

来源:二三四教育网

广告图片肯定是通过一个接口从网络异步请求, 如果让我们的app安装之后就显示, 这样的话肯定会出现一开始打开app一片空白的情况, 所以在第一次安装时, 先不显示广告, 只显示引导页, 在后台请求广告图并缓存, 等第二次启动及以后再显示

我们需要配合NSUserDefault存储图片名字, 便于下次取出之后拼接沙河路径取出使用

首先声明一个全局静态变量

static NSString *const NAImageName = @"NAImageName";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}中

先利用NSUserDefault保存的图片名, 取出并拼接成沙盒路径去查找是否存有广告图, 有则进行显示, 没有直接进入app首页

//1.判断沙盒中是否存在广告图片, 如果存在, 直接显示, 不存在就先进入app首页
    NSString *filePath = [self getFilePathWithImageName:[[NSUserDefaults standardUserDefaults] valueForKey:NAImageName]];
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    //如果图片存在
    if (isExist) {
        //展示
        NAAdView *adView = [[NAAdView alloc] initWithFrame:self.window.bounds];
        adView.filePath = filePath;
        [adView show];
    }
    else{
        NSLog(@"图片不存在");
    }

当然, 无论是否存在, 每次启动都要请求接口确保本地存的广告图是最新的

//2.无论存不存在, 都进行网络请求获取最新的网络图片, 然后存入沙盒
[self requestAdImage];

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}

出来之后, 以下是拼接沙河路径的方法

- (NSString *)getFilePathWithImageName:(NSString *)imageName{

    if (imageName) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *filePath = [paths.firstObject stringByAppendingPathComponent:imageName];
//        NSLog(@"%@", filePath);
        return filePath;
    }
    return nil;
}

网络获取图片这一块, 因为暂时没有接口, 就用一个数组存了若干图片url, 每次随机取出一个, 取url最后一段作为图片名

#pragma mark - 网络获取图片
- (void)requestAdImage{

    NSArray *imageArray =    
    NSString *imageUrl = imageArray[arc4random() % imageArray.count];

    //把获取的网址字符串按"/"分割成几部分组成数组
    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];
    }
}

检查这条文件路径是否存在

#pragma mark - 检查文件路径是否存在
- (BOOL)isFileExistWithFilePath:(NSString *)filePath{

    BOOL isDirectory = NO;
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
}

如果不存在, 开始异步下载

#pragma mark - 异步下载图片
- (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]) {
        
            [self deleteOldImage];
            [[NSUserDefaults standardUserDefaults] setValue:imageName forKey:NAImageName];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else{
            NSLog(@"保存失败");
        }
    });
}

如果存储了新图片, 那就把旧图片删除

#pragma mark - 删除旧图片
- (void)deleteOldImage{

    NSString *imageName = [[NSUserDefaults standardUserDefaults] valueForKey:NAImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

==============我是分割线=========================

以上是appDelegate我们需要做的

接下来是广告图的页面

创建一个NAAdView继承于UIView

在.h中把图片存储路径属性和开始展示的方法声明出去

来到.m

声明了以下这几个属性

@property (nonatomic, strong) UIImageView *imageViewOfAd;//广告图
@property (nonatomic, strong) UIButton *buttonOfCount;//退出按钮
@property (nonatomic, strong) NSTimer *timer;//计时器
@property (nonatomic, assign) NSInteger count;//监听当前倒数的数字

先声明一个静态常量用于规定倒计时的数字, 方便以后进行更改

static NSInteger const showTime = 3;

接下来就是重写初始化方法, 配置子视图和计时器, 并添加轻拍手势, 用于发送通知让首页push到广告页

- (instancetype)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        [self configSubviews];
    }
    return self;
}

#pragma mark - 配置子视图
- (void)configSubviews{

    //1.广告图
    _imageViewOfAd = [[UIImageView alloc] initWithFrame:self.frame];
    _imageViewOfAd.userInteractionEnabled = YES;
    _imageViewOfAd.contentMode = UIViewContentModeScaleAspectFill;
    _imageViewOfAd.clipsToBounds = YES;
    [self addSubview:_imageViewOfAd];

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


    //2.跳过按钮
    CGFloat btnW = 60;
    CGFloat btnH = 30;
    _buttonOfCount = [UIButton buttonWithType:UIButtonTypeCustom];
    _buttonOfCount.frame = CGRectMake(SCREEN_WIDTH - btnW - 24, btnH, btnW, btnH);
    [_buttonOfCount addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonOfCount setTitle:[NSString stringWithFormat:@"跳过%ld", showTime] forState:UIControlStateNormal];
    _buttonOfCount.titleLabel.font = [UIFont systemFontOfSize:15];
    [_buttonOfCount setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _buttonOfCount.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
    [self addSubview:_buttonOfCount];



    //3.定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

#pragma mark - 计时器事件
- (void)timerAction:(NSTimer *)timer{

    _count--;
    [_buttonOfCount setTitle:[NSString stringWithFormat:@"跳过%ld", _count] forState:UIControlStateNormal];
    if(_count == 0){
    
        //计时器失效, 页面退下
        [self dismiss:nil];
    }
}

#pragma mark - 轻拍手势响应事件, 跳转到广告页
- (void)pushToAdPage:(UITapGestureRecognizer *)tap{

    [self dismiss:nil];

    //发送通知让界面跳转
    [[NSNotificationCenter defaultCenter] postNotificationName:@"goToAdPage" object:nil];
}

#pragma mark - 页面消失
- (void)dismiss:(UIButton *)button{

    [_timer invalidate];
    _timer = nil;

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

只有当这个show方法在appDelegate被调用, 视图才会被添加到UIWindow上, 计时器才会加入到runLoop开始执行, 外部也会赋值一个沙盒路径进来, 让NAAdView的imageView取出图片来使用

#pragma mark - 开始展示
- (void)show{

    [self startTimer];

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

#pragma mark - 开始计时
- (void)startTimer{

    _count = showTime;
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

#pragma mark - 重写图片路径setter
- (void)setFilePath:(NSString *)filePath{

    _filePath = filePath;
    _imageViewOfAd.image = [UIImage imageWithContentsOfFile:filePath];


    NSLog(@"^^^^^%@", filePath);
}

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务