-------------------ADView视图--.h文件-------
#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 advertiseImageName = @"advertiseImageName";
//static NSString* const adUrl = @"adUrl";
/**
显示广告
*/
@interface ADView : UIView
/**
显示广告页面方法
*/
- (void)show;
/**
广告图片路径
*/
@property (nonatomic,copy) NSString* advertiseFilePath;
@end
-----------ADView.m-------------------------------
#import "ADView.h"
@interface ADView()
@property (nonatomic,strong)UIImageView* adImageView;
@property (nonatomic,strong)UIButton* skipButton;
@property (nonatomic,strong)NSTimer* counterTimer;
@property (nonatomic,assign)int count;
@end
/**
广告显示时间
*/
static int const showTime = 8;
@implementation ADView
- (NSTimer *)counterTimer{
if (!_counterTimer) {
_counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(counterDown) userInfo:nil repeats:YES];
}
return _counterTimer;
}
#pragma mark---计时器
- (void)counterDown{
_count --;
[_skipButton setTitle:[NSString stringWithFormat:@"跳过%d",_count] forState:UIControlStateNormal];
if (_count == 0) {
[self dismiss];
}
}
#pragma mark---初始化视图
/**
使用代码自定义视图的时候的注意事项:
1.要重写UIView的initWithFrame:方法而不是init方法;
理由:当外部调用init方法的时候,其内部也会默默地调用initWithFrame:方法。我们不能保证别的人在调用我们的类的时候不会直接调用initWithFrame:方法,这时如果仅重写了init方法,那么它的子空件便无法创建。
2.如果我们在创建子控件的时候,切忌如下
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
UIImageView* imageView = [[UIImageView alloc]init];
[self addSubview:imageView];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
return self;
}
理由:问题主要出现在imageView的frame赋值的地方。imageView的宽和高是直接用的self.frame.size.width,但在这个时候self.frame是可能没有值的。视图的init方法,也会执行到这里,这时候frame还没有赋值
3.不要在构造方法里面直接取本身(self或者说是本视图)的宽高,这时候取到的宽高时不准的
所以在重新构造方法的时候,我们只需要把控件放进去,暂时不要考虑它们的位置,如下
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
UIImageView* imageView = [[UIImageView alloc]init];
[self addSubview:imageView];
}
return self;
}
最典型的例子就是:在我们自定义tableViewCell的时候。重写cell的初始化方法向cell添加控件时,如label.frame = CGRectMake(0,self.frame.size.height - 20, 100, 20),我们会发现实际的y值是44-20,而不是我们设置的cell的高度-20
3.在layoutSubviews方法里面布局子控件,但是一定要先调用其父类如下
-(void)layoutSubviews{
[super layoutSubviews];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
4,另外我们也可以在构造方法之外创建子控件,声明为属性,使用懒加载,重写其get方法也是不错的
*/
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
/*添加子控件*/
//广告图片
_adImageView = [[UIImageView alloc]init];
[self addSubview:_adImageView];
_adImageView.contentMode = UIViewContentModeScaleAspectFill;
_adImageView.clipsToBounds = YES;
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pushToAdertise)];
[_adImageView addGestureRecognizer:tap];
//跳过按钮
_skipButton = [[UIButton alloc]init];
[self addSubview:_skipButton];
[_skipButton setTitle:[NSString stringWithFormat:@"跳过%d",showTime] forState:UIControlStateNormal];
_skipButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
[_skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_skipButton.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
[_skipButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
#pragma mark---布局视图子控件
- (void)layoutSubviews{
[super layoutSubviews];
//广告图片
_adImageView.frame = self.bounds;
//跳过按钮
CGFloat btnW = 60;
CGFloat btnH = 30;
_skipButton.frame = CGRectMake(screenWidth - btnW-24, btnH, btnW, btnH);
_skipButton.layer.cornerRadius = 4;
}
#pragma mark---移除广告视图
- (void)dismiss{
[self.counterTimer invalidate];//从运行循环中移除,对运行循环的饮用进行一次release
self.counterTimer = nil;//将定时器销毁--这样可以避免控制器不死
[UIView animateWithDuration:0.3f animations:^{
self.alpha = 0.f;
}completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
#pragma mark-----广告详情页面
- (void)pushToAdertise{
[self dismiss];
[[NSNotificationCenter defaultCenter]postNotificationName:@"pushToAdvertise" object:nil userInfo:nil];
}
#pragma mark---广告路径
- (void)setAdvertiseFilePath:(NSString *)advertiseFilePath{
_advertiseFilePath = advertiseFilePath;
_adImageView.image = [UIImage imageWithContentsOfFile:advertiseFilePath];
}
#pragma mark-----显示广告
- (void)show{
//倒计时方法1:GCD
// [self startGCDCountDown];
//倒计时方法二:定时器
[self startTimer];
UIWindow* window = [UIApplication sharedApplication].keyWindow;
[window addSubview:self];
}
#pragma mark---定时器倒计时
- (void)startTimer{
_count = showTime;
[[NSRunLoop mainRunLoop]addTimer:self.counterTimer forMode:NSRunLoopCommonModes];
}
#pragma mark----GCD倒计时
- (void)startGCDCountDown{
__block int timeout = showTime + 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(), ^{
[_skipButton setTitle:[NSString stringWithFormat:@"跳过%d",timeout] forState:UIControlStateNormal];
});
timeout --;
}
});
dispatch_resume(_timer);
}
@end
---------ADViewController.h-----
#import@interface ADViewController : UIViewController
@property (nonatomic,copy) NSString* adUrl;
@end
-----------------------ADViewController.m----
#import "ADViewController.h"
@interface ADViewController ()
@end
@implementation ADViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"广告";
UIWebView* webView= [[UIWebView alloc]init];
[self.view addSubview:webView];
webView.backgroundColor = [UIColor whiteColor];
webView.frame = self.view.frame;
if (!self.adUrl) {
self.adUrl = @"http://www.jianshu.com";
}
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.adUrl]]];
}
-(void)setAdUrl:(NSString *)adUrl{
_adUrl = adUrl;
}
---------------AppDelegate.m文件----
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
HtmlViewController* htmlVC = [[HtmlViewController alloc]init];
UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:htmlVC];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
//1.判断沙盒中是否存在广告图片,如果存在,就直接显示
NSString* filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
BOOL isExist = [self isFileExistWIthFilePath:filePath];
if (isExist) {//图片存在
ADView* adview = [[ADView alloc]init];
adview.frame = self.window.bounds;
adview.advertiseFilePath = filePath;
[adview show];
}
//2.无论沙盒中是否存在广告图片,都需要重新调用广告接口,判断广告是否更新
[self initAdvertisingView];
return YES;
}
/*
判断文件是否存在
*/
- (BOOL)isFileExistWIthFilePath:(NSString *)filePath{
NSFileManager* fileManager = [NSFileManager defaultManager];
BOOL isDirectory = FALSE;
return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}
/*
初始化广告页面
*/
- (void)initAdvertisingView{
NSArray *imageArray = @[@"http://imgsrc.baidu.com/forum/pic/item/9213b07eca80653846dc8fab97dda144ad348257.jpg", @"http://pic.paopaoche.net/up/2012-2/20122220201612322865.png", @"http://img5.pcpop.com/ArticleImages/picshow/0x0/20110801/2011080114495843125.jpg", @"http://www.mangowed.com/uploads/allimg/130410/1-130410215449417.jpg"];
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 downloadAdvertiseImageWithUrl:imageUrl imageName:imageName];
}
}
/*
下载新图片
*/
- (void)downloadAdvertiseImageWithUrl:(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 delteOldCachesImage];
[kUserDefaults setValue:imageName forKey:adImageName];
[kUserDefaults synchronize];
}else{
NSLog(@"保存失败");
}
});
}
/*
删除就图片
*/
- (void)delteOldCachesImage{
NSString* imageName = [kUserDefaults 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 firstObject]stringByAppendingPathComponent:imageName];
return filePath;
}
return nil;
}
------------HtmlViewController.m视图-----
@implementation HtmlViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushToAdd) name:@"pushtoad" object:nil];
[self initBacefield];//界面初始化
// [self loadWebView];//承载webview页面
// [self initBase64];
// [self initFileManager];//文件管理
// [self initMap];
// [self initSweep];
// [self initTextField];
}
-(void)pushToAdd{
ADViewController* adVC =[[ADViewController alloc]init];
[self.navigationController pushViewController:adVC animated:YES];
}