forked from duckduckgo/iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppDelegate.swift
679 lines (555 loc) · 26.9 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//
// AppDelegate.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Combine
import Common
import Core
import UserNotifications
import Kingfisher
import WidgetKit
import BackgroundTasks
import BrowserServicesKit
import Bookmarks
import Persistence
import Crashes
import Configuration
import Networking
import DDGSync
import SyncDataProviders
// swiftlint:disable file_length
// swiftlint:disable type_body_length
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// swiftlint:enable type_body_length
private static let ShowKeyboardOnLaunchThreshold = TimeInterval(20)
private struct ShortcutKey {
static let clipboard = "com.duckduckgo.mobile.ios.clipboard"
}
private var testing = false
var appIsLaunching = false
var overlayWindow: UIWindow?
var window: UIWindow?
private lazy var privacyStore = PrivacyUserDefaults()
private var bookmarksDatabase: CoreDataDatabase = BookmarksDatabase.make()
private var appTrackingProtectionDatabase: CoreDataDatabase = AppTrackingProtectionDatabase.make()
private var autoClear: AutoClear?
private var showKeyboardIfSettingOn = true
private var lastBackgroundDate: Date?
private(set) var syncService: DDGSyncing!
private(set) var syncDataProviders: SyncDataProviders!
private var syncDidFinishCancellable: AnyCancellable?
// MARK: lifecycle
// swiftlint:disable:next function_body_length cyclomatic_complexity
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if targetEnvironment(simulator)
if ProcessInfo.processInfo.environment["UITESTING"] == "true" {
// Disable hardware keyboards.
let setHardwareLayout = NSSelectorFromString("setHardwareLayout:")
UITextInputMode.activeInputModes
// Filter `UIKeyboardInputMode`s.
.filter({ $0.responds(to: setHardwareLayout) })
.forEach { $0.perform(setHardwareLayout, with: nil) }
}
#endif
// Can be removed after a couple of versions
cleanUpMacPromoExperiment2()
APIRequest.Headers.setUserAgent(DefaultUserAgentManager.duckDuckGoUserAgent)
Configuration.setURLProvider(AppConfigurationURLProvider())
CrashCollection.start {
Pixel.fire(pixel: .dbCrashDetected, withAdditionalParameters: $0, includedParameters: [.appVersion])
}
clearTmp()
_ = DefaultUserAgentManager.shared
testing = ProcessInfo().arguments.contains("testing")
if testing {
_ = DefaultUserAgentManager.shared
Database.shared.loadStore { _, _ in }
bookmarksDatabase.loadStore { context, error in
guard let context = context else {
fatalError("Error: \(error?.localizedDescription ?? "<unknown>")")
}
let legacyStorage = LegacyBookmarksCoreDataStorage()
legacyStorage?.loadStoreAndCaches()
LegacyBookmarksStoreMigration.migrate(from: legacyStorage,
to: context)
legacyStorage?.removeStore()
}
window?.rootViewController = UIStoryboard.init(name: "LaunchScreen", bundle: nil).instantiateInitialViewController()
return true
}
removeEmailWaitlistState()
Database.shared.loadStore { context, error in
guard let context = context else {
let parameters = [PixelParameters.applicationState: "\(application.applicationState.rawValue)",
PixelParameters.dataAvailability: "\(application.isProtectedDataAvailable)"]
switch error {
case .none:
fatalError("Could not create database stack: Unknown Error")
case .some(CoreDataDatabase.Error.containerLocationCouldNotBePrepared(let underlyingError)):
Pixel.fire(pixel: .dbContainerInitializationError,
error: underlyingError,
withAdditionalParameters: parameters)
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create database stack: \(underlyingError.localizedDescription)")
case .some(let error):
Pixel.fire(pixel: .dbInitializationError,
error: error,
withAdditionalParameters: parameters)
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create database stack: \(error.localizedDescription)")
}
}
DatabaseMigration.migrate(to: context)
}
bookmarksDatabase.loadStore { context, error in
guard let context = context else {
if let error = error {
Pixel.fire(pixel: .bookmarksCouldNotLoadDatabase,
error: error)
} else {
Pixel.fire(pixel: .bookmarksCouldNotLoadDatabase)
}
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create Bookmarks database stack: \(error?.localizedDescription ?? "err")")
}
let legacyStorage = LegacyBookmarksCoreDataStorage()
legacyStorage?.loadStoreAndCaches()
LegacyBookmarksStoreMigration.migrate(from: legacyStorage,
to: context)
legacyStorage?.removeStore()
WidgetCenter.shared.reloadAllTimelines()
}
appTrackingProtectionDatabase.loadStore { context, error in
guard context != nil else {
if let error = error {
Pixel.fire(pixel: .appTPCouldNotLoadDatabase, error: error)
} else {
Pixel.fire(pixel: .appTPCouldNotLoadDatabase)
}
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create AppTP database stack: \(error?.localizedDescription ?? "err")")
}
}
Favicons.shared.migrateFavicons(to: Favicons.Constants.maxFaviconSize) {
WidgetCenter.shared.reloadAllTimelines()
}
PrivacyFeatures.httpsUpgrade.loadDataAsync()
// assign it here, because "did become active" is already too late and "viewWillAppear"
// has already been called on the HomeViewController so won't show the home row CTA
AtbAndVariantCleanup.cleanup()
DefaultVariantManager().assignVariantIfNeeded { _ in
// MARK: perform first time launch logic here
DaxDialogs.shared.primeForUse()
}
// MARK: Sync initialisation
syncDataProviders = SyncDataProviders(bookmarksDatabase: bookmarksDatabase)
syncService = DDGSync(dataProvidersSource: syncDataProviders, errorEvents: SyncErrorHandler(), log: .syncLog)
syncService.initializeIfNeeded(isInternalUser: InternalUserStore().isInternalUser)
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
guard let main = storyboard.instantiateInitialViewController(creator: { coder in
MainViewController(coder: coder,
bookmarksDatabase: self.bookmarksDatabase,
appTrackingProtectionDatabase: self.appTrackingProtectionDatabase,
syncService: self.syncService)
}) else {
fatalError("Could not load MainViewController")
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = main
window?.makeKeyAndVisible()
autoClear = AutoClear(worker: main)
autoClear?.applicationDidLaunch()
clearLegacyAllowedDomainCookies()
AppDependencyProvider.shared.voiceSearchHelper.migrateSettingsFlagIfNecessary()
// Task handler registration needs to happen before the end of `didFinishLaunching`, otherwise submitting a task can throw an exception.
// Having both in `didBecomeActive` can sometimes cause the exception when running on a physical device, so registration happens here.
AppConfigurationFetch.registerBackgroundRefreshTaskHandler()
WindowsBrowserWaitlist.shared.registerBackgroundRefreshTaskHandler()
RemoteMessaging.registerBackgroundRefreshTaskHandler(bookmarksDatabase: bookmarksDatabase)
UNUserNotificationCenter.current().delegate = self
window?.windowScene?.screenshotService?.delegate = self
ThemeManager.shared.updateUserInterfaceStyle(window: window)
appIsLaunching = true
return true
}
private func cleanUpMacPromoExperiment2() {
UserDefaults.standard.removeObject(forKey: "com.duckduckgo.ios.macPromoMay23.exp2.cohort")
}
private func clearTmp() {
let tmp = FileManager.default.temporaryDirectory
do {
try FileManager.default.removeItem(at: tmp)
} catch {
os_log("Failed to delete tmp dir")
}
}
private func clearLegacyAllowedDomainCookies() {
let domains = PreserveLogins.shared.legacyAllowedDomains
guard !domains.isEmpty else { return }
WebCacheManager.shared.removeCookies(forDomains: domains, completion: {
os_log("Removed cookies for %d legacy allowed domains", domains.count)
PreserveLogins.shared.clearLegacyAllowedDomains()
})
}
func applicationDidBecomeActive(_ application: UIApplication) {
guard !testing else { return }
syncService.initializeIfNeeded(isInternalUser: InternalUserStore().isInternalUser)
if !(overlayWindow?.rootViewController is AuthenticationViewController) {
removeOverlay()
}
StatisticsLoader.shared.load {
StatisticsLoader.shared.refreshAppRetentionAtb()
self.fireAppLaunchPixel()
self.fireAppTPActiveUserPixel()
}
if appIsLaunching {
appIsLaunching = false
onApplicationLaunch(application)
}
mainViewController?.showBars()
mainViewController?.didReturnFromBackground()
if !privacyStore.authenticationEnabled {
showKeyboardOnLaunch()
}
if AppConfigurationFetch.shouldScheduleRulesCompilationOnAppLaunch {
ContentBlocking.shared.contentBlockingManager.scheduleCompilation()
AppConfigurationFetch.shouldScheduleRulesCompilationOnAppLaunch = false
}
AppConfigurationFetch().start { result in
if case .assetsUpdated(let protectionsUpdated) = result, protectionsUpdated {
ContentBlocking.shared.contentBlockingManager.scheduleCompilation()
}
}
WindowsBrowserWaitlist.shared.fetchInviteCodeIfAvailable { error in
guard error == nil else { return }
WindowsBrowserWaitlist.shared.sendInviteCodeAvailableNotification()
}
BGTaskScheduler.shared.getPendingTaskRequests { tasks in
let hasWindowsBrowserWaitlistTask = tasks.contains { $0.identifier == WindowsBrowserWaitlist.backgroundRefreshTaskIdentifier }
if !hasWindowsBrowserWaitlistTask {
WindowsBrowserWaitlist.shared.scheduleBackgroundRefreshTask()
}
}
syncService.scheduler.notifyAppLifecycleEvent()
}
private func fireAppLaunchPixel() {
WidgetCenter.shared.getCurrentConfigurations { result in
let paramKeys: [WidgetFamily: String] = [
.systemSmall: PixelParameters.widgetSmall,
.systemMedium: PixelParameters.widgetMedium,
.systemLarge: PixelParameters.widgetLarge
]
switch result {
case .failure(let error):
Pixel.fire(pixel: .appLaunch, withAdditionalParameters: [
PixelParameters.widgetError: "1",
PixelParameters.widgetErrorCode: "\((error as NSError).code)",
PixelParameters.widgetErrorDomain: (error as NSError).domain
])
case .success(let widgetInfo):
let params = widgetInfo.reduce([String: String]()) {
var result = $0
if let key = paramKeys[$1.family] {
result[key] = "1"
}
return result
}
Pixel.fire(pixel: .appLaunch, withAdditionalParameters: params)
}
}
}
private func fireAppTPActiveUserPixel() {
#if APP_TRACKING_PROTECTION
guard AppDependencyProvider.shared.featureFlagger.isFeatureOn(.appTrackingProtection) else {
return
}
let manager = FirewallManager()
Task {
await manager.refreshManager()
let date = Date()
let key = "appTPActivePixelFired"
// Make sure we don't fire this pixel multiple times a day
let dayStart = Calendar.current.startOfDay(for: date)
let fireDate = UserDefaults.standard.object(forKey: key) as? Date
if fireDate == nil || fireDate! < dayStart, manager.status() == .connected {
Pixel.fire(pixel: .appTPActiveUser)
UserDefaults.standard.set(date, forKey: key)
}
}
#endif
}
private func shouldShowKeyboardOnLaunch() -> Bool {
guard let date = lastBackgroundDate else { return true }
return Date().timeIntervalSince(date) > AppDelegate.ShowKeyboardOnLaunchThreshold
}
private func showKeyboardOnLaunch() {
guard KeyboardSettings().onAppLaunch && showKeyboardIfSettingOn && shouldShowKeyboardOnLaunch() else { return }
self.mainViewController?.enterSearch()
showKeyboardIfSettingOn = false
}
private func onApplicationLaunch(_ application: UIApplication) {
beginAuthentication()
initialiseBackgroundFetch(application)
applyAppearanceChanges()
refreshRemoteMessages()
}
private func applyAppearanceChanges() {
UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).numberOfLines = 0
}
private func refreshRemoteMessages() {
Task {
try? await RemoteMessaging.fetchAndProcess(bookmarksDatabase: self.bookmarksDatabase)
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
ThemeManager.shared.updateUserInterfaceStyle()
beginAuthentication()
autoClear?.applicationWillMoveToForeground()
showKeyboardIfSettingOn = true
syncService.scheduler.resumeSyncQueue()
}
func applicationDidEnterBackground(_ application: UIApplication) {
displayBlankSnapshotWindow()
autoClear?.applicationDidEnterBackground()
lastBackgroundDate = Date()
AppDependencyProvider.shared.autofillLoginSession.endSession()
suspendSync()
}
private func suspendSync() {
if syncService.isSyncInProgress {
os_log(.debug, log: .syncLog, "Sync is in progress. Starting background task to allow it to gracefully complete.")
var taskID: UIBackgroundTaskIdentifier!
taskID = UIApplication.shared.beginBackgroundTask(withName: "Cancelled Sync Completion Task") {
os_log(.debug, log: .syncLog, "Forcing background task completion")
UIApplication.shared.endBackgroundTask(taskID)
}
syncDidFinishCancellable?.cancel()
syncDidFinishCancellable = syncService.isSyncInProgressPublisher.filter { !$0 }
.prefix(1)
.receive(on: DispatchQueue.main)
.sink { _ in
os_log(.debug, log: .syncLog, "Ending background task")
UIApplication.shared.endBackgroundTask(taskID)
}
}
syncService.scheduler.cancelSyncAndSuspendSyncQueue()
}
func application(_ application: UIApplication,
performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void) {
handleShortCutItem(shortcutItem)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
os_log("App launched with url %s", log: .lifecycleLog, type: .debug, url.absoluteString)
NotificationCenter.default.post(name: AutofillLoginListAuthenticator.Notifications.invalidateContext, object: nil)
mainViewController?.clearNavigationStack()
autoClear?.applicationWillMoveToForeground()
showKeyboardIfSettingOn = false
if AppDeepLinks.isNewSearch(url: url) {
mainViewController?.newTab(reuseExisting: true)
if url.getParameter(named: "w") != nil {
Pixel.fire(pixel: .widgetNewSearch)
mainViewController?.enterSearch()
}
} else if AppDeepLinks.isLaunchFavorite(url: url) {
let query = AppDeepLinks.query(fromLaunchFavorite: url)
mainViewController?.loadQueryInNewTab(query, reuseExisting: true)
Pixel.fire(pixel: .widgetFavoriteLaunch)
} else if AppDeepLinks.isQuickLink(url: url) {
let query = AppDeepLinks.query(fromQuickLink: url)
mainViewController?.loadQueryInNewTab(query, reuseExisting: true)
} else if AppDeepLinks.isAddFavorite(url: url) {
mainViewController?.startAddFavoriteFlow()
} else if app.applicationState == .active,
let currentTab = mainViewController?.currentTab {
// If app is in active state, treat this navigation as something initiated form the context of the current tab.
mainViewController?.tab(currentTab,
didRequestNewTabForUrl: url,
openedByPage: true,
inheritingAttribution: nil)
} else {
Pixel.fire(pixel: .defaultBrowserLaunch)
mainViewController?.loadUrlInNewTab(url, reuseExisting: true, inheritedAttribution: nil)
}
return true
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
os_log(#function, log: .lifecycleLog, type: .debug)
AppConfigurationFetch().start(isBackgroundFetch: true) { result in
switch result {
case .noData:
completionHandler(.noData)
case .assetsUpdated:
completionHandler(.newData)
}
}
}
func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
return true
}
// MARK: private
private func initialiseBackgroundFetch(_ application: UIApplication) {
guard UIApplication.shared.backgroundRefreshStatus == .available else {
return
}
// BackgroundTasks will automatically replace an existing task in the queue if one with the same identifier is queued, so we should only
// schedule a task if there are none pending in order to avoid the config task getting perpetually replaced.
BGTaskScheduler.shared.getPendingTaskRequests { tasks in
let hasConfigurationTask = tasks.contains { $0.identifier == AppConfigurationFetch.Constants.backgroundProcessingTaskIdentifier }
if !hasConfigurationTask {
AppConfigurationFetch.scheduleBackgroundRefreshTask()
}
let hasRemoteMessageFetchTask = tasks.contains { $0.identifier == RemoteMessaging.Constants.backgroundRefreshTaskIdentifier }
if !hasRemoteMessageFetchTask {
RemoteMessaging.scheduleBackgroundRefreshTask()
}
}
}
private func displayAuthenticationWindow() {
guard overlayWindow == nil, let frame = window?.frame else { return }
overlayWindow = UIWindow(frame: frame)
overlayWindow?.windowLevel = UIWindow.Level.alert
overlayWindow?.rootViewController = AuthenticationViewController.loadFromStoryboard()
overlayWindow?.makeKeyAndVisible()
window?.isHidden = true
}
private func displayBlankSnapshotWindow() {
guard overlayWindow == nil, let frame = window?.frame else { return }
guard autoClear?.isClearingEnabled ?? false || privacyStore.authenticationEnabled else { return }
overlayWindow = UIWindow(frame: frame)
overlayWindow?.windowLevel = UIWindow.Level.alert
let overlay = BlankSnapshotViewController.loadFromStoryboard()
overlay.delegate = self
overlayWindow?.rootViewController = overlay
overlayWindow?.makeKeyAndVisible()
window?.isHidden = true
}
private func beginAuthentication() {
guard privacyStore.authenticationEnabled else { return }
removeOverlay()
displayAuthenticationWindow()
guard let controller = overlayWindow?.rootViewController as? AuthenticationViewController else {
removeOverlay()
return
}
controller.beginAuthentication { [weak self] in
self?.removeOverlay()
self?.showKeyboardOnLaunch()
}
}
private func tryToObtainOverlayWindow() {
for window in UIApplication.shared.windows where window.rootViewController is BlankSnapshotViewController {
overlayWindow = window
return
}
}
private func removeOverlay() {
if overlayWindow == nil {
tryToObtainOverlayWindow()
}
if let overlay = overlayWindow {
overlay.isHidden = true
overlayWindow = nil
window?.makeKeyAndVisible()
}
}
private func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) {
os_log("Handling shortcut item: %s", log: .generalLog, type: .debug, shortcutItem.type)
mainViewController?.clearNavigationStack()
autoClear?.applicationWillMoveToForeground()
if shortcutItem.type == ShortcutKey.clipboard, let query = UIPasteboard.general.string {
mainViewController?.loadQueryInNewTab(query)
}
}
private func removeEmailWaitlistState() {
EmailWaitlist.removeEmailState()
let autofillStorage = EmailKeychainManager()
try? autofillStorage.deleteWaitlistState()
// Remove the authentication state if this is a fresh install.
if !Database.shared.isDatabaseFileInitialized {
try? autofillStorage.deleteAuthenticationState()
}
}
private var mainViewController: MainViewController? {
return window?.rootViewController as? MainViewController
}
}
extension AppDelegate: BlankSnapshotViewRecoveringDelegate {
func recoverFromPresenting(controller: BlankSnapshotViewController) {
if overlayWindow == nil {
tryToObtainOverlayWindow()
}
overlayWindow?.isHidden = true
overlayWindow = nil
window?.makeKeyAndVisible()
}
}
extension AppDelegate: UIScreenshotServiceDelegate {
func screenshotService(_ screenshotService: UIScreenshotService,
generatePDFRepresentationWithCompletion completionHandler: @escaping (Data?, Int, CGRect) -> Void) {
guard let webView = mainViewController?.currentTab?.webView else {
completionHandler(nil, 0, .zero)
return
}
let zoomScale = webView.scrollView.zoomScale
// The PDF's coordinate space has its origin at the bottom left, so the view's origin.y needs to be converted
let visibleBounds = CGRect(
x: webView.scrollView.contentOffset.x / zoomScale,
y: (webView.scrollView.contentSize.height - webView.scrollView.contentOffset.y - webView.bounds.height) / zoomScale,
width: webView.bounds.width / zoomScale,
height: webView.bounds.height / zoomScale
)
webView.createPDF { result in
let data = try? result.get()
completionHandler(data, 0, visibleBounds)
}
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.banner)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
if response.notification.request.identifier == WindowsBrowserWaitlist.notificationIdentitier {
presentWindowsBrowserWaitlistSettingsModal()
}
}
completionHandler()
}
private func presentWindowsBrowserWaitlistSettingsModal() {
let waitlistViewController = WindowsWaitlistViewController(nibName: nil, bundle: nil)
presentSettings(with: waitlistViewController)
}
private func presentSettings(with viewController: UIViewController) {
guard let window = window, let rootViewController = window.rootViewController as? MainViewController else { return }
rootViewController.clearNavigationStack()
// Give the `clearNavigationStack` call time to complete.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
rootViewController.performSegue(withIdentifier: "Settings", sender: nil)
let navigationController = rootViewController.presentedViewController as? UINavigationController
navigationController?.popToRootViewController(animated: false)
navigationController?.pushViewController(viewController, animated: true)
}
}
}