ios-开屏广告图

1.广告页加载思路。广告页的内容要实时显示,在无网络状态或者网速缓慢的情况下不能延迟加载,或者等到首页出现了再加载广告页。所以这里我不采用网络请求广告接口获取图片地址,然后加载图片的方式,而是先将图片异步下载到本地,并保存图片名,每次打开app时先根据本地存储的图片名查找沙盒中是否存在该图片,如果存在,则显示广告页。

2.判断广告页面是否更新。无论本地是否存在广告图片,每次启动都需要重新调用广告接口,根据图片名称或者图片id等方法判断广告是否更新,如果获取的图片名称或者图片id跟本地存储的不一致,则需要重新下载新图片,并删除旧图片。

3.广告页点击。如果点击广告需要跳转广告详情页面,那么广告链接地址也需要用NSUserDefaults存储。注意:广告详情页面是从首页push进去的。

4.广告页的显示代码可以放在AppDeleate中,也可以放在首页的控制器中。如果代码是在AppDelegate中,可以通过发送通知的方式,让首页push到广告详情页。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
AppDeleate.m

//开机广告
NSString *filePath = [self getFilePathWithImageName:[DXSave Get:adImageName]];
BOOL isExist = [self isFileExistWithFilePath:filePath];
if (isExist) {// 图片存在
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *getImageUrl = [H5_SERVER stringByAppendingString:@"admin/ios_open_ads/ios_get_ad"];
[manager GET:getImageUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([self isFileExistWithFilePath: [self getFilePathWithImageName:responseObject[@"name"]]]){
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSLocale* locale = [NSLocale autoupdatingCurrentLocale];
[df setLocale: locale];
[DXSave Save:@"showTime" with:responseObject[@"show_time"]];
NSDate* startTime = [df dateFromString: responseObject[@"start_time"]];
NSDate* endTime = [df dateFromString: responseObject[@"end_time"]];
NSDate *today = [NSDate date];
if (([startTime compare:today] == NSOrderedSame || [startTime compare:today] ==NSOrderedAscending)&&
([endTime compare:today] == NSOrderedSame || [endTime compare:today] ==NSOrderedDescending) ){
[DXSave Save:@"showAd" with:@"yes"];
startAd *advertiseView = [[startAd alloc] initWithFrame:self.window.bounds];
advertiseView.filePath =[self getFilePathWithImageName:[DXSave Get:adImageName]];
[advertiseView show];
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD showErrorWithStatus:@"网络繁忙, 请稍后再试"];
}];

}
// 2.无论沙盒中是否存在广告图片,都需要重新调用广告接口,判断广告是否更新
[self getAdvertisingImage];

调用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 判断文件是否存在
*/
- (BOOL)isFileExistWithFilePath:(NSString *)filePath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = FALSE;
return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

/**
* 初始化广告页面
*/
- (void)getAdvertisingImage
{
// TODO 请求广告接口
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *getImageUrl = [H5_SERVER stringByAppendingString:@"admin/ios_open_ads/ios_get_ad"];
[manager GET:getImageUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *imageUrl = responseObject[@"img"];
NSString *imageName = responseObject[@"name"];
[DXSave Save:@"showTime" with:responseObject[@"show_time"]];
NSString *filePath = [self getFilePathWithImageName:imageName];
BOOL isExist = [self isFileExistWithFilePath:filePath];
if (!isExist){// 如果该图片不存在,则下载新图片,删除老图片
[self downloadAdImageWithUrl:imageUrl imageName:imageName url:responseObject[@"url"]];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// [SVProgressHUD showErrorWithStatus:@"网络繁忙, 请稍后再试"];
}];

}
/**
* 下载新图片
*/
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName url:(NSString*)url
{
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]; // 保存文件的名称
[DXSave Save:@"adPath" with:filePath];
if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
NSLog(@"保存成功");
[self deleteOldImage];
[DXSave Save:adImageName with:imageName];
[DXSave Save:adImageUrl with:url];
}else{
NSLog(@"保存失败");
}

});
}

/**
* 删除旧图片
*/
- (void)deleteOldImage
{
NSString *imageName = [DXSave Get: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;
}

广告页面(uiView)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
startAd.m


#import "startAd.h"

@interface startAd()
@property (nonatomic, strong) UIImageView *adView;

@property (nonatomic, strong) UIButton *countBtn;

@property (nonatomic, strong) NSTimer *countTimer;

@property (nonatomic, assign) int count;

@end

@implementation startAd

- (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.image = [UIImage imageWithContentsOfFile:_filePath];
_adView.contentMode = UIViewContentModeScaleAspectFill;
_adView.clipsToBounds = YES;
if(![[DXSave Get:@"adImageUrl"] isEqualToString:@""]){
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];
[_adView addGestureRecognizer:tap];
}

// 2.跳过按钮
CGFloat btnW = 60;
CGFloat btnH = 30;
_countBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - btnW - 24, btnH, btnW, btnH)];
[_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
[_countBtn setTitle:[NSString stringWithFormat:@"跳过%d", [[DXSave Get:@"showTime"] intValue]] 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 dismiss];
[[NSNotificationCenter defaultCenter] postNotificationName:@"pushtoad" object:nil userInfo:nil];
}

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

- (void)show
{
// 倒计时方法:定时器
[self startTimer];
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[window addSubview:self];
}

// 定时器倒计时
- (void)startTimer
{
_count = [[DXSave Get:@"showTime"] intValue];
[[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

// GCD倒计时
- (void)startCoundown
{
__block int timeout = [[DXSave Get:@"showTime"] intValue] + 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:@"跳过%d",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];
}];

}


@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
startAd.h


#import <UIKit/UIKit.h>
#define kUserDefaults [NSUserDefaults standardUserDefaults]
static NSString *const adImageName = @"adImageName";
static NSString *const adImageUrl = @"adImageUrl";
static NSString *const adUrl = @"adUrl";
@interface startAd : UIView

/** 显示广告页面方法*/
- (void)show;
/** 图片路径*/
@property (nonatomic, copy) NSString *filePath;

@end

最后首页加跳转链接

1
2
3
4
5
6
7
8
9
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToAd) name:@"pushtoad" object:nil];
}

- (void)pushToAd {
loadUrlViewController *adVc = [[loadUrlViewController alloc] init];
adVc.currentRoute = [DXSave Get:@"adImageUrl"];
[self.navigationController pushViewController:adVc animated:YES];
}