美文网首页
iOS 启动广告

iOS 启动广告

作者: CoderLGL | 来源:发表于2019-06-21 16:10 被阅读0次

    思路
    1.判断广告文件是否存在,以及初始化广告位
    2.无论沙盒中是否存在广告图片,都需要重新调用获取广告接口,判断广告是否更新
    3.异步下载图片,以及删除旧图片
    4.广告页面的跳过按钮倒计时功能可以通过定时器或者GCD实现
    5.为广告页面添加一个点击手势,跳转到广告页面

    .h

    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    static NSString *const adImageName = @"adImageName";
    
    typedef void(^TapBlock)(void);
    
    @interface GLAdView : UIView
    
    - (instancetype)initWithFrame:(CGRect)frame withTapBlock:(TapBlock)tapBlock;
    
    
    /** 图片路径*/
    @property (nonatomic, copy) NSString *filePath;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    .m

    #import "GLAdView.h"
    
    @interface GLAdView()
    
    @property (nonatomic, strong) UIImageView *adView;
    
    @property (nonatomic, strong) UIButton *countBtn;
    
    @property (nonatomic, strong) NSTimer *countTimer;
    
    @property (nonatomic, assign) int count;
    
    @property (nonatomic, copy) TapBlock tapBlock;
    
    @end
    
    // 广告显示的时间
    static int const showtime = 5;
    
    @implementation GLAdView
    
    - (NSTimer *)countTimer
    {
        if (!_countTimer) {
            _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
        }
        return _countTimer;
    }
    
    
    - (instancetype)initWithFrame:(CGRect)frame withTapBlock:(TapBlock)tapBlock
    {
        if (self = [super initWithFrame:frame]) {
            
            // 1.广告图片
            _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];
            
            // 2.跳过按钮
            CGFloat btnW = 60;
            CGFloat btnH = 30;
            _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(KScreenWidth - btnW - 24, kTopHeight, btnW, btnH)];
            [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
            [_countBtn setTitle:[NSString stringWithFormat:@"跳过%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];
            
            // 1.判断沙盒中是否存在广告图片,如果存在,直接显示
            NSString *filePath = [self getFilePathWithImageName:[[NSUserDefaults standardUserDefaults] valueForKey:adImageName]];
            
            BOOL isExist = [self isFileExistWithFilePath:filePath];
            if (isExist) {// 图片存在
                [self setFilePath:filePath];
                self.tapBlock = tapBlock;
                [self show];
            }
            // 2.无论沙盒中是否存在广告图片,都需要重新调用广告接口,判断广告是否更新
            [self getAdvertisingImage];
            
        }
        return self;
    }
    
    - (void)setFilePath:(NSString *)filePath
    {
        _filePath = filePath;
        _adView.image = [UIImage imageWithContentsOfFile:filePath];
    }
    
    - (void)pushToAd{
        
        [self dismiss];
        
        if (self.tapBlock) {
            self.tapBlock();
        }
        
    }
    
    - (void)countDown
    {
        _count --;
        [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",_count] forState:UIControlStateNormal];
        if (_count <= 0) {
            [self dismiss];
        }
    }
    
    - (void)show
    {
        // 倒计时方法2:定时器
        if (showtime<=0) {
            return;
        }
        [self startTimer];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
    }
    
    // 定时器倒计时
    - (void)startTimer
    {
        _count = showtime;
        [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
    }
    
    // 移除广告页面
    - (void)dismiss
    {
        [self.countTimer invalidate];
        self.countTimer = nil;
        
        [UIView animateWithDuration:0.3f animations:^{
            self.alpha = 0.f;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
        
    }
    
    
    /**
     *  判断文件是否存在
     */
    - (BOOL)isFileExistWithFilePath:(NSString *)filePath
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDirectory = FALSE;
        return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
    }
    
    /**
     *  初始化广告页面
     */
    - (void)getAdvertisingImage
    {
        
        NSArray *imageArray = @[@"http://img5.imgtn.bdimg.com/it/u=3300305952,1328708913&fm=26&gp=0.jpg", @"http://pic.58pic.com/58pic/13/82/74/92q58PICeSI_1024.jpg", @"http://pic25.nipic.com/20121205/10197997_003647426000_2.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];
            
        }
    }
    /**
     *  下载新图片
     */
    - (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]) {// 保存成功
                DLog(@"广告页保存成功");
                [self deleteOldImage];
                [[NSUserDefaults standardUserDefaults] setValue:imageName forKey:adImageName];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 如果有广告链接,将广告链接也保存下来
            }else{
                DLog(@"广告页保存失败");
            }
            
        });
    }
    
    /**
     *  删除旧图片
     */
    - (void)deleteOldImage
    {
        NSString *imageName = [[NSUserDefaults standardUserDefaults] valueForKey:adImageName];
        if (imageName) {
            NSString *filePath = [self getFilePathWithImageName:imageName];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:filePath error:nil];
        }
    }
    
    /**
     *  根据图片名拼接文件路径
     */
    - (NSString *)getFilePathWithImageName:(NSString *)imageName
    {
        if (imageName) {
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
            
            return filePath;
        }
        
        return nil;
    }
    
    @end
    
    

    相关文章

      网友评论

          本文标题:iOS 启动广告

          本文链接:https://www.haomeiwen.com/subject/xyopoqtx.html