iOS-啟動頁加廣告視圖

-------------------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];

}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末歉糜,一起剝皮案震驚了整個濱河市乘寒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌匪补,老刑警劉巖伞辛,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件烂翰,死亡現(xiàn)場離奇詭異,居然都是意外死亡蚤氏,警方通過查閱死者的電腦和手機甘耿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來竿滨,“玉大人佳恬,你說我怎么就攤上這事∮谟危” “怎么了毁葱?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長贰剥。 經(jīng)常有香客問我倾剿,道長,這世上最難降的妖魔是什么鸠澈? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任柱告,我火速辦了婚禮,結果婚禮上笑陈,老公的妹妹穿的比我還像新娘际度。我一直安慰自己,他們只是感情好涵妥,可當我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布乖菱。 她就那樣靜靜地躺著,像睡著了一般蓬网。 火紅的嫁衣襯著肌膚如雪窒所。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天帆锋,我揣著相機與錄音吵取,去河邊找鬼。 笑死锯厢,一個胖子當著我的面吹牛皮官,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播实辑,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼捺氢,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了剪撬?” 一聲冷哼從身側(cè)響起摄乒,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后馍佑,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體斋否,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年挤茄,在試婚紗的時候發(fā)現(xiàn)自己被綠了如叼。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡穷劈,死狀恐怖笼恰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情歇终,我是刑警寧澤社证,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站评凝,受9級特大地震影響追葡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜奕短,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一宜肉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧翎碑,春花似錦谬返、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至莉擒,卻和暖如春酿炸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背涨冀。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工填硕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鹿鳖。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓扁眯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親栓辜。 傳聞我的和親對象是個殘疾皇子恋拍,可洞房花燭夜當晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容