介绍一个几乎每个 APP 都要用的功能,APP 启动的进场广告,本来想把 ios android 都做成 Demo 放到 github 上,考虑时间关系还是算了吧,但是保证这里代码都是可运行的。
先介绍 ios ,后面把 android 和服务端的代码也贴出来。
需求逻辑是这样的:广告不是一成不变,要随时更换图片,上下架时间,以及要启动就展示,需要先存到本地,以及点击跳转等问题。下面结合代码说吧
服务端返回的数据格式,接口请求放在 AppDelegate的didFinishLaunchingWithOptions方法里
adver = (
{
endtime = 1516622424;
id = 7;
link = "https://www.baidu.com";
pic = "/uploads/image/18/01/5a65608db3ebb.png";
}
);
拿到数据保存到本地:
// 进场广告
NSMutableArray *ad_pics_array = [result.data objectForKey:@"adver"];
if (ad_pics_array && ad_pics_array.count > 0) {
NSDate *endTime = [NSDate dateWithTimeIntervalSince1970:[[[ad_pics_array objectAtIndex:0] objectForKey:@"endtime"] doubleValue]];
// 进场广告_存有效时间
[[NSUserDefaults standardUserDefaults] setObject:endTime forKey:AD_PICS_ENDTIME];
if (ad_pics_array && ad_pics_array.count > 0) {
dispatch_once(&picDownloadToken, ^{
[self performSelectorInBackground:@selector(picDownloadData:) withObject:ad_pics_array];
});
}
[[NSUserDefaults standardUserDefaults] setObject:GETTEXT([ad_pics_array objectAtIndex:0], @"link") forKey:AD_PICS_CONNECT];
} else {
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:AD_PICS_ENDTIME];
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:AD_PICS_CONNECT];
}
- (void)picDownloadData:(NSArray*)ad_pics_array {
NSString *picUrl = [[ad_pics_array objectAtIndex:0] objectForKey:@"pic"];
NSString *picUrl_local = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_ADDRESS];
if (![picUrl isEqualToString:picUrl_local]) {
NSLog(@"执行图片下载");
NSString *urlString = [Constant getImgHttpAdress:[[ad_pics_array objectAtIndex:0] objectForKey:@"pic"]];
NSLog(@"====>%@",urlString);
NSData * picData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[urlString remoteImageAspectFill:SCREEN_WIDTH * [UIScreen mainScreen].scale height:SCREEN_HEIGHT * [UIScreen mainScreen].scale noScale:NO]]];
if (picData) {
UIImage * imageFromURL = [UIImage imageWithData:picData];
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"保存路径:%@",documentsDirectoryPath);
[UIImageJPEGRepresentation(imageFromURL, 0.8) writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", @"adPic", @"jpg"]] options:NSAtomicWrite error:nil];
// 进场广告_存图片地址
[[NSUserDefaults standardUserDefaults] setObject:picUrl forKey:AD_PICS_ADDRESS];
}
}
}
加载进场广告,建议放在AppDelegate的didFinishLaunchingWithOptions方法里,当然也可以放在第一个 viewCtroller 里:
- (void)ad_pic_show {
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//字符串拼接得到文件完整路径
NSString *ad_pic_name = @"/adPic.jpg";
NSString *ad_pic_path = [documentsDirectoryPath stringByAppendingString:ad_pic_name];
NSLog(@"完整路径是:%@",ad_pic_path);
NSData *ad_pic_data = [NSData dataWithContentsOfFile:ad_pic_path];
if (ad_pic_data){
UIImage *ad_pic_image = [UIImage imageWithData:ad_pic_data];
NSDate *endTime = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_ENDTIME];
NSDate *nowTime = [NSDate date];
if ([endTime isEqualToDate:[endTime laterDate:nowTime]] && ad_pic_image){
[ADLaunchView showAdView:ad_pic_image];
}
}
}
ADLaunchView.h 和ADLaunchView.m:
#import
@interface ADLaunchView : UIView
@property (nonatomic, strong) UIImage *adImage;
+ (void)showAdView:(UIImage *)adImage;
@end
#import "ADLaunchView.h"
#import "LoginHomeViewController.h"
#import "Community-Swift.h"
@implementation ADLaunchView {
NSTimer *m_pTimer;
int inputSeconds;
UILabel *secLabel;
UIButton *contentBtn;
UIImageView *adimg;
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
adimg = [[UIImageView alloc]initWithFrame:frame];
adimg.backgroundColor = [UIColor orangeColor];
[self addSubview:adimg];
adimg.userInteractionEnabled = YES;
contentBtn = [[UIButton alloc] initWithFrame:adimg.bounds];
contentBtn.backgroundColor = [UIColor clearColor];
[contentBtn addTarget:self action:@selector(contentBtnAction) forControlEvents:UIControlEventTouchUpInside];
[adimg addSubview:contentBtn];
UIView * timeBg = [[UIView alloc]initWithFrame:CGRectMake(frame.size.width-80, 30, 65, 30)];
timeBg.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
timeBg.layer.cornerRadius = 15;
timeBg.clipsToBounds = YES;
timeBg.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.3];
[adimg addSubview:timeBg];
timeBg.userInteractionEnabled = YES;
UITapGestureRecognizer *popTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction)];
[timeBg addGestureRecognizer:popTap];
UILabel * woldLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 32, 20)];
woldLabel.text = @"跳过";
woldLabel.textColor = [UIColor whiteColor];
woldLabel.textAlignment = 1;
woldLabel.font = [UIFont systemFontOfSize:15.0];
[timeBg addSubview:woldLabel];
secLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(woldLabel.frame), 5, 20, 20)];
secLabel.textColor = [Constant colorOfDefined:@"#ff9900"];
secLabel.font = [UIFont systemFontOfSize:15.0];
secLabel.textAlignment = 1;
[timeBg addSubview: secLabel];
inputSeconds = 3;
secLabel.text = [NSString stringWithFormat:@"%d",inputSeconds];
m_pTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self selector:@selector(calcuRemainTime)
userInfo:nil repeats:YES];
}
return self;
}
- (void)setAdImage:(UIImage *)adImage {
adimg.image = adImage;
}
/*
*倒计时剩余时间计算
*/
- (void)calcuRemainTime
{
inputSeconds--;
if (inputSeconds >= 0) {
secLabel.text = [NSString stringWithFormat:@"%d",inputSeconds];
}
if (inputSeconds <= 0.0) {
[m_pTimer invalidate];
m_pTimer = nil;
[self closeAction];
}
}
- (void)closeAction {
self.userInteractionEnabled = NO;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
// 动画选项设定
animation.duration = 1.5; // 动画持续时间
animation.repeatCount = 0; // 重复次数
animation.autoreverses = NO; // 动画结束时执行逆动画
animation.delegate = self;
// 缩放倍数
animation.fromValue = [NSNumber numberWithFloat:1.0]; // 开始时的倍率
animation.toValue = [NSNumber numberWithFloat:1.5]; // 结束时的倍率
// 添加动画
[self.layer addAnimation:animation forKey:@"scale-layer"];
[UIView animateWithDuration:0.6 animations:^{
self.alpha = 0;
} completion:^(BOOL finished) {
// [self removeFromSuperview];
}];
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
if (flag) {
[self removeFromSuperview];
}
}
- (void)contentBtnAction {
NSString *link = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_CONNECT];
if (link) {
SQ_OPEN(link, @"");
[self closeAction];
for (UIViewController *vc in [AppDelegate sharedAppDelegate].topNavigationController.viewControllers) {
if ([vc isKindOfClass:[LoginHomeViewController class]]) {
[vc removeFromParentViewController];
[[AppDelegate sharedAppDelegate].topNavigationController setNavigationBarHidden:NO animated:YES];
break;
}
}
}
}
+ (void)showAdView:(UIImage *)adImage1 {
ADLaunchView *adView = [[ADLaunchView alloc] initWithFrame:[UIScreen mainScreen].bounds];
adView.adImage = adImage1;
[[AppDelegate sharedAppDelegate].window addSubview:adView];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
这里会有一个小问题就是更换了广告图片 或者应用第一次打开是不展示广告的 ~~因为第一次的时候我要把图片保存下来,很好理解。