-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathAppDelegate.swift
177 lines (143 loc) · 7.33 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
//
// Copyright 2013 - 2021 Anton Tananaev (anton@traccar.org)
//
// 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 CoreData
import Firebase
import IntentsUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PositionProviderDelegate {
var window: UIWindow?
var managedObjectContext: NSManagedObjectContext?
var managedObjectModel: NSManagedObjectModel?
var persistentStoreCoordinator: NSPersistentStoreCoordinator?
var trackingController: TrackingController?
var positionProvider: PositionProvider?
static var instance: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
#if FIREBASE
FirebaseApp.configure()
#endif
UIDevice.current.isBatteryMonitoringEnabled = true
let userDefaults = UserDefaults.standard
if userDefaults.string(forKey: "device_id_preference") == nil {
let identifier = "\(Int.random(in: 100000..<1000000))"
userDefaults.setValue(identifier, forKey: "device_id_preference")
}
registerDefaultsFromSettingsBundle()
migrateLegacyDefaults()
let modelUrl = Bundle.main.url(forResource: "TraccarClient", withExtension: "momd")
managedObjectModel = NSManagedObjectModel(contentsOf: modelUrl!)
persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
let storeUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.appendingPathComponent("TraccarClient.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
try! persistentStoreCoordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: options)
managedObjectContext = NSManagedObjectContext.init(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext?.persistentStoreCoordinator = persistentStoreCoordinator
if userDefaults.bool(forKey: "service_status_preference") {
StatusViewController.addMessage(NSLocalizedString("Service created", comment: ""))
trackingController = TrackingController()
trackingController?.start()
}
return true
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
let userDefaults = UserDefaults.standard
switch shortcutItem.type {
case "org.traccar.client.start":
if !userDefaults.bool(forKey: "service_status_preference") {
userDefaults.setValue(true, forKey: "service_status_preference")
StatusViewController.addMessage(NSLocalizedString("Service created", comment: ""))
trackingController = TrackingController()
trackingController?.start()
showToast(message: NSLocalizedString("Service created", comment: ""))
}
case "org.traccar.client.stop":
if userDefaults.bool(forKey: "service_status_preference") {
userDefaults.setValue(false, forKey: "service_status_preference")
StatusViewController.addMessage(NSLocalizedString("Service destroyed", comment: ""))
trackingController?.stop()
trackingController = nil
showToast(message: NSLocalizedString("Service destroyed", comment: ""))
}
case "org.traccar.client.sos":
positionProvider = PositionProvider()
positionProvider?.delegate = self
positionProvider?.startUpdates()
default:
break
}
completionHandler(true)
}
func didUpdate(position: Position) {
positionProvider?.stopUpdates()
positionProvider = nil
let userDefaults = UserDefaults.standard
if let request = ProtocolFormatter.formatPostion(position, url: userDefaults.string(forKey: "server_url_preference")!, alarm: "sos") {
RequestManager.sendRequest(request, completionHandler: {(_ success: Bool) -> Void in
if success {
self.showToast(message: NSLocalizedString("Send successfully", comment: ""))
} else {
self.showToast(message: NSLocalizedString("Send failed", comment: ""))
}
})
}
}
func showToast(message : String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
window?.rootViewController?.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
alert.dismiss(animated: true)
}
}
func applicationWillTerminate(_ application: UIApplication) {
if let context = managedObjectContext {
if context.hasChanges {
try! context.save()
}
}
}
func registerDefaultsFromSettingsBundle() {
let settingsBundle = Bundle.main.path(forResource: "InAppSettings", ofType: "bundle")!
let finalPath = URL(fileURLWithPath: settingsBundle).appendingPathComponent("Root.plist")
let settingsDictionary = NSDictionary(contentsOf: finalPath)
let preferenceSpecifiers = settingsDictionary?.object(forKey: "PreferenceSpecifiers") as! [NSDictionary]
var defaults: [String:Any] = [:]
for item in preferenceSpecifiers {
if let key = item.object(forKey: "Key") as? String {
defaults[key] = item.object(forKey: "DefaultValue")
}
}
UserDefaults.standard.register(defaults: defaults)
}
func migrateLegacyDefaults() {
let userDefaults = UserDefaults.standard
if userDefaults.object(forKey: "server_address_preference") != nil {
var urlComponents = URLComponents()
urlComponents.scheme = userDefaults.bool(forKey: "secure_preference") ? "https" : "http"
urlComponents.host = userDefaults.string(forKey: "server_address_preference")
urlComponents.port = userDefaults.integer(forKey: "server_port_preference")
if urlComponents.port == 0 {
urlComponents.port = 5055
}
userDefaults.set(urlComponents.string, forKey: "server_url_preference")
userDefaults.removeObject(forKey: "server_port_preference")
userDefaults.removeObject(forKey: "server_address_preference")
userDefaults.removeObject(forKey: "secure_preference")
}
}
}