AppDelegate.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. //
  2. // AppDelegate.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14 (19/02/21 swift).
  6. // Copyright (c) 2014 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import BackgroundTasks
  25. import NCCommunication
  26. import TOPasscodeViewController
  27. import LocalAuthentication
  28. import Firebase
  29. @UIApplicationMain
  30. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TOPasscodeViewControllerDelegate {
  31. var backgroundSessionCompletionHandler: (() -> Void)?
  32. var window: UIWindow?
  33. @objc var account: String = ""
  34. @objc var urlBase: String = ""
  35. @objc var user: String = ""
  36. @objc var userID: String = ""
  37. @objc var password: String = ""
  38. var activeFavorite: NCFavorite?
  39. var activeFiles: NCFiles?
  40. var activeFileViewInFolder: NCFileViewInFolder?
  41. var activeLogin: CCLogin?
  42. var activeLoginWeb: NCLoginWeb?
  43. @objc var activeMedia: NCMedia?
  44. var activeMore: NCMore?
  45. var activeOffline: NCOffline?
  46. var activeRecent: NCRecent?
  47. var activeServerUrl: String = ""
  48. var activeShares: NCShares?
  49. var activeTransfers: NCTransfers?
  50. var activeTrash: NCTrash?
  51. var activeViewController: UIViewController?
  52. var activeViewerVideo: NCViewerVideo?
  53. struct progressType {
  54. var progress: Float
  55. var totalBytes: Int64
  56. var totalBytesExpected: Int64
  57. }
  58. var listFilesVC: [String:NCFiles] = [:]
  59. var listFavoriteVC: [String:NCFavorite] = [:]
  60. var listOfflineVC: [String:NCOffline] = [:]
  61. var listProgress: [String:progressType] = [:]
  62. var disableSharesView: Bool = false
  63. var documentPickerViewController: NCDocumentPickerViewController?
  64. var networkingAutoUpload: NCNetworkingAutoUpload?
  65. var passcodeViewController: TOPasscodeViewController?
  66. var pasteboardOcIds: [String] = []
  67. var shares: [tableShare] = []
  68. var ncUserDefaults: UserDefaults?
  69. @objc var timerErrorNetworking: Timer?
  70. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  71. let userAgent = CCUtility.getUserAgent() as String
  72. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  73. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  74. UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])
  75. if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service == false {
  76. FirebaseApp.configure()
  77. }
  78. CCUtility.createDirectoryStandard()
  79. CCUtility.emptyTemporaryDirectory()
  80. NCCommunicationCommon.shared.setup(delegate: NCNetworking.shared)
  81. NCCommunicationCommon.shared.setup(userAgent: userAgent)
  82. startTimerErrorNetworking()
  83. // LOG
  84. let levelLog = CCUtility.getLogLevel()
  85. NCCommunicationCommon.shared.levelLog = levelLog
  86. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  87. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  88. }
  89. NCCommunicationCommon.shared.copyLogToDocumentDirectory = true
  90. if isSimulatorOrTestFlight {
  91. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  92. } else {
  93. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  94. }
  95. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain(notification:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterInitializeMain), object: nil)
  96. if let tableAccount = NCManageDatabase.shared.getAccountActive() {
  97. // FIX 3.0.5 lost urlbase
  98. if tableAccount.urlBase.count == 0 {
  99. let user = tableAccount.user + " "
  100. let urlBase = tableAccount.account.replacingOccurrences(of: user, with: "")
  101. tableAccount.urlBase = urlBase
  102. NCManageDatabase.shared.updateAccount(tableAccount)
  103. }
  104. settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userID: tableAccount.userID, password: CCUtility.getPassword(tableAccount.account))
  105. } else {
  106. CCUtility.deleteAllChainStore()
  107. if let bundleID = Bundle.main.bundleIdentifier {
  108. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  109. }
  110. }
  111. ncUserDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups)
  112. // Push Notification
  113. application.registerForRemoteNotifications()
  114. UNUserNotificationCenter.current().delegate = self
  115. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
  116. // AV
  117. do {
  118. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  119. try AVAudioSession.sharedInstance().setActive(true)
  120. } catch {
  121. print(error)
  122. }
  123. application.beginReceivingRemoteControlEvents()
  124. // Store review
  125. if !NCUtility.shared.isSimulatorOrTestFlight() {
  126. let review = NCStoreReview()
  127. review.incrementAppRuns()
  128. review.showStoreReview()
  129. }
  130. // Detect Dark mode
  131. if #available(iOS 13.0, *) {
  132. if CCUtility.getDarkModeDetect() {
  133. if UITraitCollection.current.userInterfaceStyle == .dark {
  134. CCUtility.setDarkMode(true)
  135. } else {
  136. CCUtility.setDarkMode(false)
  137. }
  138. }
  139. }
  140. if NCBrandOptions.shared.disable_intro {
  141. CCUtility.setIntro(true)
  142. if account == "" {
  143. openLogin(viewController: nil, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: false)
  144. }
  145. } else {
  146. if !CCUtility.getIntro() {
  147. if let introViewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  148. let navController = UINavigationController(rootViewController: introViewController)
  149. window?.rootViewController = navController
  150. window?.makeKeyAndVisible()
  151. }
  152. }
  153. }
  154. // init home
  155. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterInitializeMain)
  156. // Passcode
  157. DispatchQueue.global().async {
  158. self.passcodeWithAutomaticallyPromptForBiometricValidation(true)
  159. }
  160. // Auto upload
  161. networkingAutoUpload = NCNetworkingAutoUpload.init()
  162. // Background task: register
  163. if #available(iOS 13.0, *) {
  164. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCBrandGlobal.shared.refreshTask, using: nil) { task in
  165. self.handleRefreshTask(task)
  166. }
  167. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCBrandGlobal.shared.processingTask, using: nil) { task in
  168. self.handleProcessingTask(task)
  169. }
  170. } else {
  171. application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  172. }
  173. return true
  174. }
  175. // L' applicazione entrerà in primo piano (attivo sempre)
  176. func applicationDidBecomeActive(_ application: UIApplication) {
  177. NCSettingsBundleHelper.setVersionAndBuildNumber()
  178. if account == "" { return}
  179. NCNetworking.shared.verifyUploadZombie()
  180. }
  181. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  182. func applicationWillEnterForeground(_ application: UIApplication) {
  183. if account == "" { return}
  184. NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
  185. // Request Passcode
  186. passcodeWithAutomaticallyPromptForBiometricValidation(true)
  187. // Initialize Auto upload
  188. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  189. // Required unsubscribing / subscribing
  190. NCPushNotification.shared().pushNotification()
  191. // Request Service Server Nextcloud
  192. NCService.shared.startRequestServicesServer()
  193. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationWillEnterForeground)
  194. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterRichdocumentGrabFocus)
  195. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  196. }
  197. func applicationWillResignActive(_ application: UIApplication) {
  198. if account == "" { return}
  199. if activeFileViewInFolder != nil {
  200. activeFileViewInFolder?.dismiss(animated: false, completion: {
  201. self.activeFileViewInFolder = nil
  202. })
  203. }
  204. }
  205. func applicationDidEnterBackground(_ application: UIApplication) {
  206. if account == "" { return}
  207. NCCommunicationCommon.shared.writeLog("Application did enter in background")
  208. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationDidEnterBackground)
  209. passcodeWithAutomaticallyPromptForBiometricValidation(false)
  210. if #available(iOS 13.0, *) {
  211. scheduleAppRefresh()
  212. scheduleBackgroundProcessing()
  213. }
  214. }
  215. func applicationWillTerminate(_ application: UIApplication) {
  216. NCCommunicationCommon.shared.writeLog("bye bye")
  217. }
  218. // MARK: -
  219. @objc func initializeMain(notification: NSNotification) {
  220. if account == "" { return}
  221. NCCommunicationCommon.shared.writeLog("initialize Main")
  222. // Clear error certificate
  223. CCUtility.setCertificateError(account, error: false)
  224. // Registeration push notification
  225. NCPushNotification.shared().pushNotification()
  226. // Setting Theming
  227. NCBrandColor.shared.settingThemingColor(account: account)
  228. // Start Auto Upload
  229. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  230. // Start services
  231. NCService.shared.startRequestServicesServer()
  232. // close detail
  233. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterMenuDetailClose)
  234. // Registeration domain File Provider
  235. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  236. //[fileProviderDomain removeAllDomains];
  237. //[fileProviderDomain registerDomains];
  238. }
  239. // MARK: - Background Task
  240. @available(iOS 13.0, *)
  241. func scheduleAppRefresh() {
  242. let request = BGAppRefreshTaskRequest.init(identifier: NCBrandGlobal.shared.refreshTask)
  243. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  244. do {
  245. try BGTaskScheduler.shared.submit(request)
  246. NCCommunicationCommon.shared.writeLog("Refresh task success submit request \(request)")
  247. } catch {
  248. NCCommunicationCommon.shared.writeLog("Refresh task failed to submit request: \(error)")
  249. }
  250. }
  251. @available(iOS 13.0, *)
  252. func scheduleBackgroundProcessing() {
  253. let request = BGProcessingTaskRequest.init(identifier: NCBrandGlobal.shared.processingTask)
  254. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  255. request.requiresNetworkConnectivity = true
  256. request.requiresExternalPower = false
  257. do {
  258. try BGTaskScheduler.shared.submit(request)
  259. NCCommunicationCommon.shared.writeLog("Background Processing task success submit request \(request)")
  260. } catch {
  261. NCCommunicationCommon.shared.writeLog("Background Processing task failed to submit request: \(error)")
  262. }
  263. }
  264. @available(iOS 13.0, *)
  265. func handleRefreshTask(_ task: BGTask) {
  266. if account == "" {
  267. task.setTaskCompleted(success: true)
  268. return
  269. }
  270. NCCommunicationCommon.shared.writeLog("Start handler refresh task [Auto upload]")
  271. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (items) in
  272. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  273. NCCommunicationCommon.shared.writeLog("Completition handler refresh task with %lu uploads [Auto upload]")
  274. task.setTaskCompleted(success: true)
  275. }
  276. }
  277. }
  278. @available(iOS 13.0, *)
  279. func handleProcessingTask(_ task: BGTask) {
  280. if account == "" {
  281. task.setTaskCompleted(success: true)
  282. return
  283. }
  284. NCCommunicationCommon.shared.writeLog("Start handler processing task [Synchronize Favorite & Offline]")
  285. NCNetworking.shared.listingFavoritescompletion(selector: NCBrandGlobal.shared.selectorReadFile) { (account, metadatas, errorCode, errorDescription) in
  286. NCCommunicationCommon.shared.writeLog("Completition listing favorite with error: \(errorCode)")
  287. }
  288. NCService.shared.synchronizeOffline(account: account)
  289. DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
  290. NCCommunicationCommon.shared.writeLog("Completition handler processing task [Synchronize Favorite & Offline]")
  291. task.setTaskCompleted(success: true)
  292. }
  293. }
  294. // MARK: - Fetch
  295. func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  296. if account == "" {
  297. completionHandler(UIBackgroundFetchResult.noData)
  298. return
  299. }
  300. NCCommunicationCommon.shared.writeLog("Start perform Fetch [Auto upload]")
  301. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (items) in
  302. NCCommunicationCommon.shared.writeLog("Completition perform Fetch with \(items) uploads [Auto upload]")
  303. if items == 0 {
  304. completionHandler(UIBackgroundFetchResult.noData)
  305. } else {
  306. completionHandler(UIBackgroundFetchResult.newData)
  307. }
  308. }
  309. }
  310. // MARK: - Background Networking Session
  311. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  312. NCCommunicationCommon.shared.writeLog("Start handle Events For Background URLSession: \(identifier)")
  313. backgroundSessionCompletionHandler = completionHandler
  314. }
  315. // MARK: - Push Notifications
  316. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  317. completionHandler(UNNotificationPresentationOptions.alert)
  318. }
  319. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  320. completionHandler()
  321. }
  322. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  323. NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
  324. }
  325. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  326. NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { (result) in
  327. completionHandler(result)
  328. }
  329. }
  330. // MARK: - Login & checkErrorNetworking
  331. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  332. }
  333. @objc func startTimerErrorNetworking() {
  334. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  335. }
  336. @objc func checkErrorNetworking() {
  337. if account == "" { return }
  338. // check unauthorized server (401)
  339. if CCUtility.getPasscode()?.count == 0 {
  340. openLogin(viewController: window?.rootViewController, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: true)
  341. }
  342. // check certificate untrusted (-1202)
  343. if CCUtility.getCertificateError(account) {
  344. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  345. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  346. NCNetworking.shared.writeCertificate(directoryCertificate: CCUtility.getDirectoryCerificates())
  347. self.startTimerErrorNetworking()
  348. }))
  349. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  350. self.startTimerErrorNetworking()
  351. }))
  352. window?.rootViewController?.present(alertController, animated: true, completion: {
  353. self.timerErrorNetworking?.invalidate()
  354. })
  355. }
  356. }
  357. // MARK: - Account & Communication
  358. @objc func settingAccount(_ account: String, urlBase: String, user: String, userID: String, password: String) {
  359. self.account = account
  360. self.urlBase = urlBase
  361. self.user = user
  362. self.userID = userID
  363. self.password = password
  364. _ = NCNetworkingNotificationCenter.shared
  365. NCCommunicationCommon.shared.setup(account: account, user: user, userId: userID, password: password, urlBase: urlBase)
  366. NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
  367. NCCommunicationCommon.shared.setup(dav: NCUtilityFileSystem.shared.getDAV())
  368. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  369. if serverVersionMajor > 0 {
  370. NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
  371. }
  372. }
  373. @objc func deleteAccount(_ account: String, wipe: Bool) {
  374. // Push Notification
  375. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  376. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  377. }
  378. settingAccount("", urlBase: "", user: "", userID: "", password: "")
  379. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  380. for result in results {
  381. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(result.ocId))
  382. }
  383. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  384. CCUtility.clearAllKeysEnd(toEnd: account)
  385. CCUtility.clearAllKeysPushNotification(account)
  386. CCUtility.setCertificateError(account, error: false)
  387. CCUtility.setPassword(account, password: nil)
  388. if wipe {
  389. let accounts = NCManageDatabase.shared.getAccounts()
  390. if accounts?.count ?? 0 > 0 {
  391. if let newAccount = accounts?.first {
  392. if let account = NCManageDatabase.shared.setAccountActive(newAccount) {
  393. settingAccount(account.account, urlBase: account.urlBase, user: account.user, userID: account.userID, password: CCUtility.getPassword(account.account))
  394. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterInitializeMain)
  395. }
  396. }
  397. } else {
  398. openLogin(viewController: window?.rootViewController, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: false)
  399. }
  400. }
  401. }
  402. // MARK: - TOPasscodeViewController
  403. func passcodeWithAutomaticallyPromptForBiometricValidation(_ automaticallyPromptForBiometricValidation: Bool) {
  404. let laContext = LAContext()
  405. var error: NSError?
  406. if CCUtility.getPasscode()?.count == 0 || account == "" || CCUtility.getNotPasscodeAtStart() { return }
  407. if passcodeViewController == nil {
  408. passcodeViewController = TOPasscodeViewController.init(style: .translucentLight, passcodeType: .sixDigits)
  409. if #available(iOS 13.0, *) {
  410. if UITraitCollection.current.userInterfaceStyle == .dark {
  411. passcodeViewController?.style = .translucentDark
  412. }
  413. }
  414. passcodeViewController?.delegate = self
  415. passcodeViewController?.keypadButtonShowLettering = false
  416. if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  417. if error == nil {
  418. if laContext.biometryType == .faceID {
  419. passcodeViewController?.biometryType = .faceID
  420. passcodeViewController?.allowBiometricValidation = true
  421. } else if laContext.biometryType == .touchID {
  422. passcodeViewController?.biometryType = .touchID
  423. passcodeViewController?.allowBiometricValidation = true
  424. }
  425. }
  426. }
  427. if let passcodeViewController = self.passcodeViewController {
  428. window?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  429. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  430. })
  431. }
  432. } else {
  433. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  434. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  435. }
  436. }
  437. }
  438. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  439. passcodeViewController.dismiss(animated: true) {
  440. self.passcodeViewController = nil
  441. }
  442. }
  443. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  444. return code == CCUtility.getPasscode()
  445. }
  446. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  447. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  448. if success {
  449. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  450. passcodeViewController.dismiss(animated: true) {
  451. self.passcodeViewController = nil
  452. }
  453. }
  454. }
  455. }
  456. }
  457. func enableTouchFaceID(_ automaticallyPromptForBiometricValidation: Bool) {
  458. if CCUtility.getEnableTouchFaceID() && automaticallyPromptForBiometricValidation && passcodeViewController?.view.window != nil {
  459. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  460. if success {
  461. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  462. self.passcodeViewController?.dismiss(animated: true) {
  463. self.passcodeViewController = nil
  464. }
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }