• iOS开发Swift-16-App的生命周期-AppDelegate和SceneDelegate


    AppDelegate:

    1. import UIKit
    2. import CoreData
    3. //包含App的部分生命周期函数(钩子函数),也有其余函数(如推送)
    4. @main
    5. class AppDelegate: UIResponder, UIApplicationDelegate {
    6. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    7. // Override point for customization after application launch.
    8. print("App启动")
    9. return true
    10. }
    11. // MARK: UISceneSession Lifecycle
    12. //iOS的App只有一个场景(只有一个窗口)
    13. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    14. // Called when a new scene session is being created.
    15. // Use this method to select a configuration to create the new scene with.
    16. print("即将创建一个窗口时.在此可配置一个可视窗口")
    17. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    18. }
    19. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    20. // Called when the user discards a scene session.
    21. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    22. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    23. print("用户关闭了某个窗口")
    24. }
    25. // MARK: - Core Data stack
    26. lazy var persistentContainer: NSPersistentContainer = {
    27. /*
    28. The persistent container for the application. This implementation
    29. creates and returns a container, having loaded the store for the
    30. application to it. This property is optional since there are legitimate
    31. error conditions that could cause the creation of the store to fail.
    32. */
    33. let container = NSPersistentContainer(name: "Todos")
    34. container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    35. if let error = error as NSError? {
    36. // Replace this implementation with code to handle the error appropriately.
    37. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    38. /*
    39. Typical reasons for an error here include:
    40. * The parent directory does not exist, cannot be created, or disallows writing.
    41. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
    42. * The device is out of space.
    43. * The store could not be migrated to the current model version.
    44. Check the error message to determine what the actual problem was.
    45. */
    46. fatalError("Unresolved error \(error), \(error.userInfo)")
    47. }
    48. })
    49. return container
    50. }()
    51. // MARK: - Core Data Saving support
    52. func saveContext () {
    53. let context = persistentContainer.viewContext
    54. if context.hasChanges {
    55. do {
    56. try context.save()
    57. } catch {
    58. // Replace this implementation with code to handle the error appropriately.
    59. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    60. let nserror = error as NSError
    61. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    62. }
    63. }
    64. }
    65. }

    SceneDelegate:

    1. import UIKit
    2. //包含App的UI方面的生命周期函数,也有其余函数(如从别的App跳转回来时)
    3. class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    4. var window: UIWindow?
    5. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    6. // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    7. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    8. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    9. print("若使用IB,则自动创建可视窗口;若不使用IB,则可在此利用window属性(可视窗口),然后用代码设定App的首页vc")
    10. guard let _ = (scene as? UIWindowScene) else { return }
    11. }
    12. func sceneDidDisconnect(_ scene: UIScene) {
    13. // Called as the scene is being released by the system.
    14. // This occurs shortly after the scene enters the background, or when its session is discarded.
    15. // Release any resources associated with this scene that can be re-created the next time the scene connects.
    16. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    17. print("窗口/App已经断开连接(1.关闭App时调用,2.退到后台后不久调用)")
    18. }
    19. //App主要有三种状态:被关闭,在前台,在后台
    20. //下面两个方法对应的范围更广,如App关闭时,用户点击推送横幅后打开App,也会调用sceneDidBecomeActive,此时可清楚右上角角标
    21. func sceneDidBecomeActive(_ scene: UIScene) {
    22. // Called when the scene has moved from an inactive state to an active state.
    23. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    24. print("窗口/App从非活跃-->活跃(已经被激活)")
    25. }
    26. func sceneWillResignActive(_ scene: UIScene) {
    27. // Called when the scene will move from an active state to an inactive state.
    28. // This may occur due to temporary interruptions (ex. an incoming phone call).
    29. print("窗口/App从活跃-->非活跃(即将被挂起)")
    30. }
    31. func sceneWillEnterForeground(_ scene: UIScene) {
    32. // Called as the scene transitions from the background to the foreground.
    33. // Use this method to undo the changes made on entering the background.
    34. print("窗口/App从后台-->前台(即将回到前台)")
    35. }
    36. func sceneDidEnterBackground(_ scene: UIScene) {
    37. // Called as the scene transitions from the foreground to the background.
    38. // Use this method to save data, release shared resources, and store enough scene-specific state information
    39. // to restore the scene back to its current state.
    40. print("窗口/App从前台-->后台(已经进入后台)")
    41. // Save changes in the application's managed object context when the application transitions to the background.
    42. (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
    43. }
    44. }
  • 相关阅读:
    基于Java毕业设计新疆旅游专列订票系统源码+系统+mysql+lw文档+部署软件
    【Redis】深入探索 Redis 的数据类型 —— 列表 List
    【uniapp】关于小程序输入框聚焦、失焦(输入法占位)的问题
    python经典百题之字符串长度
    越南公司注册要求
    Android 官方屏幕适配之ScreenMatch
    【LeetCode】540. 有序数组中的单一元素
    视图、储存过程、函数 e3
    C++ | 简单线程池的实现
    TensorFlow之分类模型-1
  • 原文地址:https://blog.csdn.net/LYly_B/article/details/132973870