-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
213 lines (174 loc) · 7.98 KB
/
Copy pathAppDelegate.swift
File metadata and controls
213 lines (174 loc) · 7.98 KB
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
//
// AppDelegate.swift
// iOCNotes
//
// Created by Peter Hedlund on 2/12/19.
// Copyright © 2020 Peter Hedlund. All rights reserved.
//
import UIKit
import BackgroundTasks
import NextcloudKit
import SwiftUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var store = Store.shared
var window: UIWindow?
var notesTableViewController: NotesTableViewController?
///
/// Updated by being the `NextcloudKitDelegate`.
///
var networkReachability: NKCommon.TypeReachability?
static var shared: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
private let operationQueue = OperationQueue()
private var updateFrcDelegateNeeded = true
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
NextcloudKit.shared.setup(delegate: self)
for account in store.accounts {
NextcloudKit.shared.appendSession(
account: account.id,
urlBase: account.baseURL,
user: account.userId,
userId: account.userId,
password: account.password,
userAgent: userAgent,
nextcloudVersion: account.serverVersion.major,
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup
)
}
_ = BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.peterandlinda.iOCNotes.Sync", using: nil) { task in
if let task = task as? BGAppRefreshTask {
print(task.description)
self.handleAppSync(task: task)
}
}
window?.tintColor = .ph_iconColor
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
UINavigationBar.appearance().barTintColor = .ph_popoverButtonColor
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().tintColor = .ph_iconColor
UIToolbar.appearance().barTintColor = .ph_popoverButtonColor
UIToolbar.appearance().tintColor = .ph_iconColor
UIBarButtonItem.appearance().tintColor = .ph_textColor
UITableViewCell.appearance().backgroundColor = .ph_cellBackgroundColor
let scrollViewArray = [
NotesTableViewController.self,
CategoryTableViewController.self,
EditorViewController.self,
PreviewViewController.self,
]
UIScrollView.appearance(whenContainedInInstancesOf: scrollViewArray).backgroundColor = .ph_cellBackgroundColor
UISwitch.appearance().onTintColor = .ph_switchTintColor
UISwitch.appearance().tintColor = .ph_switchTintColor
UILabel.appearance().themeColor = .ph_textColor
UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).themeColor = .ph_readTextColor
UITextField.appearance().textColor = .ph_textColor
UITextView.appearance().tintColor = .ph_selectedTextColor
let contentView = ContentView()
.environment(Store.shared)
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
notesTableViewController?.disableFetchedResultsController()
updateFrcDelegateNeeded = true
scheduleAppSync()
}
func applicationWillResignActive(_ application: UIApplication) {
if !KeychainHelper.server.isEmpty,
let server = URL(string: KeychainHelper.server),
let scheme = server.scheme, let host = server.host,
let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.nextcloud.apps") {
let account = NKShareAccounts.DataAccounts(withUrl: scheme + "://" + host, user: KeychainHelper.username)
_ = NKShareAccounts().putShareAccounts(at: dirGroupApps, app: "nextcloudnotes", dataAccounts: [account])
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
store.synchronize()
updateFrcDelegateIfNeeded()
}
private func updateFrcDelegateIfNeeded() {
guard updateFrcDelegateNeeded else {
return
}
updateFrcDelegateNeeded = false
notesTableViewController?.configureFetchedResultsController(performFetch: KeychainHelper.didSyncInBackground)
KeychainHelper.didSyncInBackground = false
}
func scheduleAppSync() {
BGTaskScheduler.shared.cancelAllTaskRequests()
let request = BGAppRefreshTaskRequest(identifier: "com.peterandlinda.iOCNotes.Sync")
request.earliestBeginDate = Date(timeIntervalSinceNow: 600)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppSync(task: BGAppRefreshTask) {
// Schedule a new refresh task
scheduleAppSync()
// Create an operation that performs the main part of the background task
let operation = SyncOperation()
// Provide an expiration handler for the background task
// that cancels the operation
task.expirationHandler = {
operation.cancel()
}
// Inform the system that the background task is complete
// when the operation completes
operation.completionBlock = {
KeychainHelper.didSyncInBackground = true
task.setTaskCompleted(success: !operation.isCancelled)
}
// Start the operation
operationQueue.addOperation(operation)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if let scheme = url.scheme, scheme == "nextcloudnotes" {
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
if let queryItems = urlComponents?.queryItems,
let item = queryItems.first(where: { $0.name == "note" }),
let content = item.value {
// Make sure we connect the delegate up, as this is called before the app is active
updateFrcDelegateIfNeeded()
self.notesTableViewController?.addNote(content: content)
}
} else if url.isFileURL {
do {
_ = url.startAccessingSecurityScopedResource()
let content = try String(contentsOf: url, encoding: .utf8)
NoteSessionManager.shared.add(content: content, category: "")
try FileManager.default.removeItem(at: url)
url.stopAccessingSecurityScopedResource()
} catch {
print(error.localizedDescription)
}
}
return true
}
}
// MARK: - NextcloudKitDelegate
extension AppDelegate: NextcloudKitDelegate {
func authenticationChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
DispatchQueue.global().async {
if let serverTrust = challenge.protectionSpace.serverTrust {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
} else {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}
}
public func networkReachabilityObserver(_ typeReachability: NKCommon.TypeReachability) {
self.networkReachability = typeReachability
}
}