和大多小白一样,第一次见到这个东西的时候觉得很简单,但实际操作起来还是要费些功夫的。
主要是启动页消失时间不好判断,
我这里是启动配置didifinishLaunch方法中window盖一张与启动图一样的图片,等到更新,广告请求信息都拿到后,去除添加的启动图。
然后建议大家,在去除广告图之前window.rootVC随意设置为一个tempVC,等到去除启动图改变RootViewController,这样做的好处是避免启动图删除时,主要的VC创建时需要的接口信息更及时准确。
import UIKit
import ICSMainFramework
import MBProgressHUD
import Async
@UIApplicationMain
private class AppDelegate: UIResponder,UIApplicationDelegate {
var launchImg :UIImageView? = nil
var adView :AdView? = nil
var uploadView :UploadView? = nil
open var bootstrapViewController: UIViewController {
return UIViewController()
}
open var window: UIWindow?
open func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let launchCG = launchConfig.init()
launchCG.setTempVC()
launchCG.launch()
return true;
}
open func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
open func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.didEnterBackground] {
for item in lifeCycleItems{
item.object?.applicationDidEnterBackground?(application)
}
}
}
open func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.willEnterForeground] {
for item in lifeCycleItems{
item.object?.applicationWillEnterForeground?(application)
}
}
}
open func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.didBecomeActive] {
for item in lifeCycleItems{
item.object?.applicationDidBecomeActive?(application)
}
}
}
open func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.willTerminate] {
for item in lifeCycleItems{
item.object?.applicationWillTerminate?(application)
}
}
}
open func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.remoteNotification] {
for item in lifeCycleItems{
item.object?.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
}
}
open func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.remoteNotification] {
for item in lifeCycleItems{
item.object?.application?(application, didFailToRegisterForRemoteNotificationsWithError: error)
}
}
}
open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.remoteNotification] {
for item in lifeCycleItems{
item.object?.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
}
}
open func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
var handled = false
if let lifeCycleItems = AppConfig.sharedConfig.lifeCycleConfig[LifeCycleKey.openURL] {
for item in lifeCycleItems{
if #available(iOSApplicationExtension 9.0, *) {
if let res = item.object?.application?(app, open: url, options: options), res{
handled = res
}
} else {
// Fallback on earlier versions
}
}
}
return handled
}
}
class launchConfig: NSObject {
fileprivate var delegate = UIApplication.shared.delegate as! AppDelegate
func getAdinfo(urlstr : String) -> Void {
AlamofireManager.shared().postAny(params: nil, api: urlstr, responseBlock: { (flag, data) -> (Void) in
self.changeRootVC()
self.delegate.launchImg?.removeFromSuperview()
if ( (data as? Dictionary<String,Any>) != nil && ((data as! Dictionary<String,Any>)[DATA_KEY] as? [Dictionary<String,Any>]) != nil){
self.delegate.adView?.isHidden = false
self.delegate.adView?.config(data: (data as! Dictionary<String,Any>)[DATA_KEY] as! [Dictionary<String,Any>])
}else{
print("广告参数错误")
self.delegate.adView?.removeFromSuperview()
}
}) { (error) -> (Void) in
print("广告参数未获取到")
self.changeRootVC()
self.delegate.launchImg?.removeFromSuperview()
self.delegate.adView?.removeFromSuperview()
}
}
func getPn(){
AlamofireManager.shared().post(params: nil, api: AppTP, responseBlock: { (flag, data) -> (Void) in
if((data["protocol"] as? String) != nil ){
UserDefaults.standard.set(data, forKey: "dvp")
UserDefaults.standard.synchronize()
}else{
}
self.getAdinfo(urlstr: AppAdApi)
}) { (error) -> (Void) in
self.getAdinfo(urlstr: AppAdApi)
}
}
func getUploadInfo() -> Void {
AlamofireManager.shared().dragDomain(params: nil, get: false, api: AppStartUrl, responseBlock: { (flag, data) -> (Void) in
if ((data["down"] as? String != nil)&&(data["ver"] as? String != nil)&&(data["web_api"] as? String != nil)){
AppLoadUrl = data["down"] as? String ?? ""
AppServerVersion = data["ver"] as? String ?? ""
AppApiDomain = data["web_api"] as? String ?? ""
AppOpen = data["open"] as? String ?? ""
// AppOpen = "1"
if(TKing() == true){
self.getPn()
}else{
self.getAdinfo(urlstr: (AppAdApi))
}
self.delegate.uploadView?.config(dic: data)
}else{
print("启动参数错误,程序可能无法正常运行")
self.changeRootVC()
self.showProgreeHUD("launchInfoNull".localized(), delay: nil)
self.delegate.uploadView?.removeFromSuperview()
self.delegate.adView?.removeFromSuperview()
self.delegate.launchImg?.removeFromSuperview()
}
}) { (error) -> (Void) in
print("启动参数未获取到")
self.changeRootVC()
self.showProgreeHUD("launchError".localized(), delay: nil)
self.delegate.adView?.removeFromSuperview()
self.delegate.uploadView?.removeFromSuperview()
self.delegate.launchImg?.removeFromSuperview()
}
}
func showProgreeHUD(_ text: String? = nil,delay : Double? = Double(HudDelayTime)) {
MBProgressHUD.hide(for: delegate.window!, animated: true)
let hud = MBProgressHUD.showAdded(to: delegate.window!, animated: true)
hud.mode = .indeterminate
hud.label.text = text
Async.main(after: delay) {
MBProgressHUD.hide(for: self.delegate.window!, animated: true)
}
}
func launch(){
self.resetLaunchViews()
self.getUploadInfo()
}
func resetLaunchViews() -> Void {
//更新页面
delegate.uploadView = UploadView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: PTTScreenWidth(), height: PTTScreenHeight()))
delegate.uploadView?.isHidden = true
delegate.window?.addSubview(delegate.uploadView!)
//广告图
delegate.adView = AdView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: PTTScreenWidth(), height: PTTScreenHeight()))
delegate.adView?.isHidden = true
delegate.window?.addSubview(delegate.adView!)
//启动图最上边
delegate.launchImg = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: PTTScreenWidth(), height: PTTScreenHeight()))
delegate.launchImg?.backgroundColor = .white
delegate.launchImg?.image = UIImage.init(named: "launchExam")
delegate.window?.addSubview(delegate.launchImg!)
}
func setTempVC() {
delegate.window = UIWindow(frame: UIScreen.main.bounds)
delegate.window?.backgroundColor = UIColor.white
delegate.window?.makeKeyAndVisible()
let tempVC = UIViewController.init()
delegate.window?.rootViewController = tempVC
}
func changeRootVC() {
let nVC = NavigationVC.init()
delegate.window?.rootViewController = nVC
if (delegate.uploadView != nil) {
delegate.window?.bringSubview(toFront: delegate.uploadView!)
}
if (delegate.adView != nil) {
delegate.window?.bringSubview(toFront: delegate.adView!)
}
if (delegate.launchImg != nil) {
delegate.window?.bringSubview(toFront: delegate.launchImg!)
}
}
}