日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

AppDelegate瘦身之服务化

發布時間:2023/12/10 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 AppDelegate瘦身之服务化 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

有沒有覺得你的AppDelegate雜亂無章?代碼幾百行上千行?集成了無數的功能,如推送、埋點、日志統計、Crash統計等等,感覺AppDelegate無所不能。

來一段一般的AppDelegate代碼,來自網上一篇文章:

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {Log(info: "AppDelegate.didFinishLaunchingSite started.")application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)UNUserNotificationCenter.current().register(delegate: self,actions: [UNNotificationAction(identifier: "favorite", title: .localized(.favorite))])// Initialize Google Analyticsif !AppGlobal.userDefaults[.googleAnalyticsID].isEmpty {GAI.sharedInstance().tracker(withTrackingId: AppGlobal.userDefaults[.googleAnalyticsID])}// Declare data format from remote REST APIJSON.dateFormatter.dateFormat = ZamzamConstants.DateTime.JSON_FORMAT// Initialize componentsAppLogger.shared.setUp()AppData.shared.setUp()// Select home tab(window?.rootViewController as? UITabBarController)?.selectedIndex = 2setupTheme()Log(info: "App finished launching.")// Handle shortcut launchif let shortcutItem = launchOptions?[.shortcutItem] as? UIApplicationShortcutItem {performActionForShortcutItem(application, shortcutItem: shortcutItem)return false}return true}func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let webpageURL = userActivity.webpageURL else { return false }Log(info: "AppDelegate.continueUserActivity for URL: \(webpageURL.absoluteString).")return navigateByURL(webpageURL)}func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {Log(info: "AppDelegate.performFetch started.")scheduleUserNotifications(completionHandler: completionHandler)}func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {window?.rootViewController?.dismiss(animated: false, completion: nil)guard let tabController = window?.rootViewController as? UITabBarController else { completionHandler?(false); return }switch shortcutItem.type {case "favorites":tabController.selectedIndex = 0case "search":tabController.selectedIndex = 3case "contact":guard let url = URL(string: "mailto:\(AppGlobal.userDefaults[.email])") else { break }UIApplication.shared.open(url)default: break}completionHandler?(true)} }// MARK: - User Notification Delegateextension AppDelegate {func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {guard let id = response.notification.request.content.userInfo["id"] as? Int,let link = response.notification.request.content.userInfo["link"] as? String,let url = try? link.asURL()else { return }switch response.actionIdentifier {case UNNotificationDefaultActionIdentifier: _ = navigateByURL(url)case "favorite": PostService().addFavorite(id)case "share": _ = navigateByURL(url)default: break}completionHandler()}private func scheduleUserNotifications(completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {// Get latest posts from server// Persist network manager instance to ensure lifespan is not interruptedurlSessionManager = PostService().updateFromRemote {guard case .success(let results) = $0 else { return completionHandler(.failed) }guard let id = results.created.first,let post = (try? Realm())?.object(ofType: Post.self, forPrimaryKey: id)else { return completionHandler(.noData) }var attachments = [UNNotificationAttachment]()// Completion process on exitfunc deferred() {// Launch notificationUNUserNotificationCenter.current().add(body: post.previewContent,title: post.title,attachments: attachments,timeInterval: 5,userInfo: ["id": post.id,"link": post.link],completion: {guard $0 == nil else { return Log(error: "Could not schedule the notification for the post: \($0.debugDescription).") }Log(debug: "Scheduled notification for post during background fetch.")})completionHandler(.newData)}// Get remote media to attach to notificationguard let link = post.media?.thumbnailLink else { return deferred() }let thread = Thread.currentUNNotificationAttachment.download(from: link) {defer { thread.async { deferred() } }guard $0.isSuccess, let attachment = $0.value else {return Log(error: "Could not download the post thumbnail (\(link)): \($0.error.debugDescription).")}// Store attachment to schedule notification laterattachments.append(attachment)}}} }// MARK: - Internal functionsprivate extension AppDelegate {func setupTheme() {window?.tintColor = UIColor(rgb: AppGlobal.userDefaults[.tintColor])if !AppGlobal.userDefaults[.titleColor].isEmpty {UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor(rgb: AppGlobal.userDefaults[.titleColor])]}// Configure tab barif let controller = window?.rootViewController as? UITabBarController {controller.tabBar.items?.get(1)?.image = UIImage(named: "top-charts", inBundle: AppConstants.bundle)controller.tabBar.items?.get(1)?.selectedImage = UIImage(named: "top-charts-filled", inBundle: AppConstants.bundle)controller.tabBar.items?.get(2)?.image = UIImage(named: "explore", inBundle: AppConstants.bundle)controller.tabBar.items?.get(2)?.selectedImage = UIImage(named: "explore-filled", inBundle: AppConstants.bundle)if !AppGlobal.userDefaults[.tabTitleColor].isEmpty {UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(rgb: AppGlobal.userDefaults[.tabTitleColor])], for: .selected)}}// Configure dark mode if applicableif AppGlobal.userDefaults[.darkMode] {UINavigationBar.appearance().barStyle = .blackUITabBar.appearance().barStyle = .blackUICollectionView.appearance().backgroundColor = .blackUITableView.appearance().backgroundColor = .blackUITableViewCell.appearance().backgroundColor = .clear}} } 復制代碼

看完后,有沒有一個類就能完成整個應用的想法?今天,我們的目的就是使得AppDelegate這個類代碼極限縮減。

如果大家有了解過微服務的話,大家就會知道,一個服務專職做一件事情,然后由網關來調度,這樣的邏輯是非常清晰的,也非常便于維護,我們這次的改造也是源于這樣的思路的。

按照上圖,以后我們的AppDelegate只做網關對應的功能,其他具體業務,交由不同的服務去做,那么,我們應該如何實現這樣的想法呢?

1.首先我們創建一個文件TDWApplicationDelegate.swift 里面的代碼:

/// UIApplicationDelegate 協議擴展 public protocol TDWApplicationDelegate: UIApplicationDelegate {} 復制代碼

這里定義了一個***TDWApplicationDelegate***,繼承***UIApplicationDelegate***。這個協議是方便以后擴展用的。

2.我們再創建一個文件TDWAppDelegateService.swift 代碼為:

import Foundationopen class TDWAppDelegateService: UIResponder, TDWApplicationDelegate {/// 啟動服務的數組open var __services:[TDWApplicationDelegate] = [] }// MARK: - 啟動 extension TDWAppDelegateService {open func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {__services.forEach {_ = $0.application?(application, didFinishLaunchingWithOptions: launchOptions)}return true} }// MARK: - 其他應用喚起 extension TDWAppDelegateService {// iOS 9.0 及以下open func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {__services.forEach {_ = $0.application?(application, open: url, sourceApplication: sourceApplication, annotation: annotation)}return true}// iOS 9.0 以上open func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {if #available(iOS 9.0, *) {__services.forEach {_ = $0.application?(app, open: url, options: options)}return true}else {return false}} }// MARK: - 前后臺 extension TDWAppDelegateService {open func applicationWillEnterForeground(_ application: UIApplication) {__services.forEach { $0.applicationWillEnterForeground?(application) }}open func applicationDidEnterBackground(_ application: UIApplication) {__services.forEach { $0.applicationDidEnterBackground?(application) }}open func applicationDidBecomeActive(_ application: UIApplication) {__services.forEach { $0.applicationDidBecomeActive?(application) }}open func applicationWillResignActive(_ application: UIApplication) {__services.forEach { $0.applicationWillResignActive?(application) }}open func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {__services.forEach{ $0.application?(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)}} }// MARK: - 退出 extension TDWAppDelegateService {open func applicationWillTerminate(_ application: UIApplication) {__services.forEach { $0.applicationWillTerminate?(application) }}open func applicationDidReceiveMemoryWarning(_ application: UIApplication) {__services.forEach { $0.applicationDidReceiveMemoryWarning?(application) }} }// MARK: - 推送相關 extension TDWAppDelegateService {open func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {__services.forEach { $0.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) }}open func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {__services.forEach { $0.application?(application, didFailToRegisterForRemoteNotificationsWithError: error) }}// NS_AVAILABLE_IOS(7_0);open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {__services.forEach { $0.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)}} }// MARK: - 3DTouch相關 extension TDWAppDelegateService {@available(iOS 9.0, *)open func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {__services.forEach { $0.application?(application, performActionFor: shortcutItem, completionHandler: completionHandler) }} } 復制代碼

這個是本文的核心類,他主要做了些什么事情呢?

1.定義了一個服務數組,把服務都統一管理。 2.在extension里面實現常用的AppDelegate生命周期的協議。因為***__services***里面的服務都是繼承于***TDWApplicationDelegate***,所以,沒有服務,其實能實現AppDelegate生命周期。所以,在這個***TDWAppDelegateService***上,我在他所有的生命周期里同步遍歷調用所有服務***__services***的對等生命周期,這樣,就變相于我收到系統的信息后,會同步給各個服務,讓他們自己處理了。

這樣,我們就完成了整個服務的框架了。那么,我們如何使用呢? 這里,我以2個服務作為例子,當然,你可以構建10個,只要你喜歡。

import TDWAppDelegateServiceclass TDWInitializeService: NSObject, TDWApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {print("TDWInitializeService")return true} }class TDWLogService: NSObject, TDWApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {print("TDWLogService")return true} } 復制代碼

這里有2個服務,一個是初始化服務,一個是日志服務,他們都只做一件事件,打印相關的字符串。

ok,下面我們構建下我們的AppDelegate:

import UIKit import TDWAppDelegateService@UIApplicationMain class AppDelegate: TDWAppDelegateService {var window: UIWindow?override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {// Override point for customization after application launch.__services = [TDWInitializeService(), TDWLogService()]return super.application(application, didFinishLaunchingWithOptions: launchOptions)}} 復制代碼

AppDelegate非常簡潔,他只有短短幾句代碼。 1.首先AppDelegate繼承于***TDWAppDelegateService*** 2.然后重載***didFinishLaunchingWithOptions***方法,把服務實例放到***__services***數組就可以了。 3.最后,你就可以運行看結果了。

沒錯,服務按順序執行對應的功能,也就是打印對應的字符串。

好了,以上就是本文要介紹的內容,歡迎評論反饋,謝謝!!

轉載于:https://juejin.im/post/5cb97755518825328e00aac2

總結

以上是生活随笔為你收集整理的AppDelegate瘦身之服务化的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 国产欧美一区二区三区精华液好吗 | 一本色道久久综合亚洲二区三区 | 国产绳艺sm调教室论坛 | 日韩av在线播放不卡 | 人妻一区二区在线 | 亚洲精品乱码久久久久久国产主播 | 国产区视频在线观看 | 在线观看一区二区三区四区 | 2022精品国偷自产免费观看 | 黑人精品无码一区二区三区AV | 久草黄色 | 天堂av免费在线观看 | 久久亚洲精少妇毛片午夜无码 | 视频在线观看电影完整版高清免费 | 激情五月深爱五月 | 日本一本高清 | 亚洲av永久无码国产精品久久 | 大香焦久久 | 中国黄色1级片 | 国产麻豆成人精品av | 亚洲永久精品ww.7491进入 | 国内少妇毛片视频 | 欧美成人三级视频 | 激情亚洲色图 | 亚洲无限看 | 亚洲视频 一区 | 成人免费视频一区二区 | 91麻豆网 | 国产日韩在线免费观看 | 亚欧在线播放 | 亚洲国产精品二区 | 美女扒开下面让男人捅 | 天天视频天天爽 | 黄网站免费在线观看 | 美女被草出白浆 | 欧美性猛交99久久久久99按摩 | 亚洲婷婷在线观看 | 国模在线视频 | 90岁肥老奶奶毛毛外套 | 精品在线二区 | 久久爰| av优选在线观看 | 日日爽爽| 亚洲熟女乱综合一区二区 | 亚洲精品国产美女 | 中文字幕在线视频日韩 | 中文字幕av免费在线观看 | 婷婷色基地 | a级片网站| 国产成人啪精品午夜在线观看 | 亚洲视频一区在线 | 伦理av在线 | 99热日本| 日本毛片网站 | 痴女扩张宫交脱垂重口小说 | 欧美另类极品videosbest最新版本 | 抽插丰满内射高潮视频 | av男人天堂网 | 毛片基地免费观看 | 玩弄少妇人妻 | 五月综合色 | 国产一区一一区高清不卡 | 日本一道在线 | 久久爱综合| 美女被男人桶出白浆喷水 | 日本黄网站 | 精品无码av一区二区三区不卡 | 亚洲 欧美 日韩 国产综合 在线 | 久久久久亚洲精品国产 | 青娱乐免费在线视频 | 狠狠操欧美 | 视色视频在线观看 | 欧美一级在线 | 一级肉体全黄裸片 | 91最新地址永久入口 | 亚洲视频高清 | 四虎影视国产精品 | av无码一区二区三区 | 亚洲色图17p | 男插女在线观看 | 国产精品美乳在线观看 | 小箩莉末发育娇小性色xxxx | 91香蕉黄 | аⅴ资源新版在线天堂 | 亚洲加勒比 | 永久免费无码av网站在线观看 | jjzz日本视频 | 亚洲欧美日韩一区 | 91丨九色丨国产在线 | 王者后宫yin肉h文催眠 | 爱爱爱爱网站 | 深夜影院在线观看 | 国产欧美综合一区 | 久久久久久久999 | 久久久久久久久久网站 | 高清无码一区二区在线观看吞精 | 成人综合网址 | wwwxxx日韩 | 69国产|