swift启动页,广告业,更新页简单处理.

和大多小白一样,第一次见到这个东西的时候觉得很简单,但实际操作起来还是要费些功夫的。

主要是启动页消失时间不好判断,

我这里是启动配置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!)
        }
    }
    
}




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swift 应用程序的启动页时间实际上也是由 iOS 应用程序的 Launch Screen 控制的。Launch Screen 是一个启动时显示的固定界面,用户在启动应用程序时会看到它。 要更改 Swift 应用程序的启动页时间,可以在 Launch Screen 的视图控制器中添加一个 Label,并使用代码设置它的值。以下是一个示例: 1. 打开 LaunchScreen.storyboard,将一个 Label 拖到视图控制器中。 2. 选中 Label,打开 Attributes inspector,在 Text 中输入“Loading...”或其他您想要显示的文本。 3. 打开 ViewController.swift 文件,添加以下代码: ``` import UIKit class ViewController: UIViewController { @IBOutlet weak var loadingLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // 设置定时器,2秒后执行 updateTime 方法 Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(updateTime), userInfo: nil, repeats: false) } @objc func updateTime() { // 更新 Label 的值 loadingLabel.text = "Done!" // 2秒后自动退出 Launch Screen Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(dismissLaunchScreen), userInfo: nil, repeats: false) } @objc func dismissLaunchScreen() { // 消失 Launch Screen self.dismiss(animated: true, completion: nil) } } ``` 4. 在视图控制器中链接 Label,将其命名为 loadingLabel。 5. 运行应用程序,您将在 Launch Screen 上看到“Loading...”文本。2秒后,它将更新为“Done!”,另外2秒后,Launch Screen 将自动消失。 这样,您就可以更改 Swift 应用程序的启动页时间了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值