-------------------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方法店诗;
理由:當外部調(diào)用init方法的時候,其內(nèi)部也會默默地調(diào)用initWithFrame:方法酱畅。我們不能保證別的人在調(diào)用我們的類的時候不會直接調(diào)用initWithFrame:方法一汽,這時如果僅重寫了init方法,那么它的子空件便無法創(chuàng)建蹬竖。
2.如果我們在創(chuàng)建子控件的時候色瘩,切忌如下
- (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;
}
理由:問題主要出現(xiàn)在imageView的frame賦值的地方锥腻。imageView的寬和高是直接用的self.frame.size.width吠勘,但在這個時候self.frame是可能沒有值的性芬。視圖的init方法,也會執(zhí)行到這里,這時候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),我們會發(fā)現(xiàn)實際的y值是44-20鸡挠,而不是我們設置的cell的高度-20
3.在layoutSubviews方法里面布局子控件辉饱,但是一定要先調(diào)用其父類如下
-(void)layoutSubviews{
[super layoutSubviews];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
4,另外我們也可以在構造方法之外創(chuàng)建子控件宵凌,聲明為屬性,使用懶加載止后,重寫其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];//從運行循環(huán)中移除瞎惫,對運行循環(huán)的飲用進行一次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);//每秒執(zhí)行
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.reibang.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.無論沙盒中是否存在廣告圖片瓜喇,都需要重新調(diào)用廣告接口,判斷廣告是否更新
[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];
}
}
/*
根據(jù)圖片名拼接文件路徑
*/
- (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];
}