首先打開AppDelegate.m
大家都知道啟動頁在加載完畢會自動執行AppDelegate didFinishLaunchingWithOptions 函數:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
所以直接將加載廣告代碼寫在這個函數里面就對了:
#import "AppDelegate.h"
@interface AppDelegate ()
//啟動頁view
@property (strong, nonatomic) UIView *LaunchView;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//創建window
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
//獲取啟動頁
UIStoryboard *LaunchScreen = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
UIViewController *LaunchVC = [LaunchScreen instantiateInitialViewController];
self.LaunchView = LaunchVC.view;
//加載遠程廣告
[self loadAD];
//設置rootView
self.window.rootViewController = LaunchVC;
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark 加載遠程廣告
- (void)loadAD
{
//遠程圖片地址
NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1486466389044&di=a7ab421bb82bd0d214bbdc5a6b79f2bf&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F17%2F80%2F57%2F94s58PICA7j_1024.jpg"];
//異步加載圖片
dispatch_queue_t queue = dispatch_queue_create("loadImage", NULL);
dispatch_async(queue, ^{
//圖片資源
NSData *imgData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:imgData];
dispatch_async(dispatch_get_main_queue(), ^{
//創建imageView
UIImageView *adView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
adView.image = img;
//添加圖片點擊手勢
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAD)];
adView.userInteractionEnabled = YES;
[adView addGestureRecognizer:singleTap];
[self.LaunchView addSubview:adView];
//LaunchView前置于window
[self.window bringSubviewToFront:self.LaunchView];
//延遲5秒后刪除廣告
[self performSelector:@selector(removeAd) withObject:nil afterDelay:5];
});
});
}
#pragma mark 廣告點擊
- (void)clickAD {
[self removeAd];
}
#pragma mark 刪除廣告
- (void)removeAd
{
[self.LaunchView removeFromSuperview];
//重新設置rootView
UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
self.window.rootViewController = [main instantiateInitialViewController];
[self.window makeKeyAndVisible];
}
PS:以上圖片素材均為網上下載
最終效果:
未命名.gif
github完整Demo:
https://github.com/sg369326973/LaunchLoadAD-Demo