Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 12 | Rev 17 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
//
2
//  AppDelegate.swift
3
//  twogetskills
4
//
5
//  Created by Efrain Yanez Recanatini on 2/23/22.
6
//
7
 
8
import Foundation
9
import Firebase
10
import Messages
11
import BackgroundTasks
12
 
13
//UIResponder, UIApplicationDelegate {
14
 
15
class AppDelegate : NSObject, UIApplicationDelegate {
15 efrain 16
    private let database = Database.sharedInstance
1 efrain 17
    private let gcmMessageIDKey = "gcm.message_id"
18
    private var appData = AppData.sharedInstance
15 efrain 19
    private var syncAdapter = SyncAdapter()
20
    private var isSyncInProgress = false
21
    private static var orientationLock = UIInterfaceOrientationMask.portrait
1 efrain 22
 
23
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
24
        return AppDelegate.orientationLock
25
    }
26
 
27
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
28
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
29
 
30
 
15 efrain 31
        database.open()
32
        database.createTables()
33
        database.close()
34
 
35
        print("observador del UUID del dispositivo")
36
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: .receivingNewDevice, object: nil)
37
 
38
        print("observador del FCM TOKEN")
39
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: .receivingNewToken, object: nil)
40
 
41
 
42
 
43
 
1 efrain 44
        if let new_uuid = UIDevice.current.identifierForVendor?.uuidString {
15 efrain 45
            let userInfo = ["uuid": new_uuid]
46
            NotificationCenter.default.post(name: .receivingNewDevice , object: self, userInfo: userInfo)
1 efrain 47
        }
48
 
49
 
50
        FirebaseApp.configure()
51
 
15 efrain 52
        Messaging.messaging().delegate = self
1 efrain 53
 
15 efrain 54
        if #available(iOS 10.0, *) {
55
            // For iOS 10 display notification (sent via APNS)
56
            UNUserNotificationCenter.current().delegate = self
1 efrain 57
 
15 efrain 58
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
59
            UNUserNotificationCenter.current().requestAuthorization(
60
                options: authOptions,
61
                completionHandler: {_, _ in })
62
        } else {
63
            let settings: UIUserNotificationSettings =
64
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
65
            application.registerUserNotificationSettings(settings)
66
        }
1 efrain 67
 
15 efrain 68
        application.registerForRemoteNotifications()
12 efrain 69
 
70
 
71
 
72
        registerBGTasksScheduler()
73
        scheduleProcess()
74
        scheduleRefresh()
75
 
76
        return true
1 efrain 77
    }
78
 
15 efrain 79
    // Storage of the UID once the notification is received
80
       @objc func receivingNewDevice(n: NSNotification){
81
 
82
            print("receivingNewDevice")
83
            if n.userInfo != nil{
84
                if let new_uuid = n.userInfo?["uuid"]! as? String {
85
                    let old_uuid = appData.deviceUuid
86
                    if new_uuid != old_uuid {
87
 
88
                        db = database.open()
89
                        if db != nil {
90
                            var sync = SyncModel()
91
                            sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
92
                            sync.data = new_uuid
93
 
94
                            let syncDao = SyncDao(db : db)
95
                            if syncDao.insert(record: sync) > 0 {
96
                                appData.deviceUuid = new_uuid
97
                                appData.save()
98
 
99
                                syncAdapter.sync {
100
                                        success in
101
                                }
102
                            }
103
                        }
104
                        database.close()
105
 
106
 
107
                    }
108
                }
109
            }
110
        }
111
 
112
        @objc func receivingNewToken(n: NSNotification){
113
            if n.userInfo != nil{
114
                if let token = n.userInfo?["token"]! as? String {
115
                    if !token.isEmpty {
116
                        if appData.fcmToken != token  {
117
 
118
                            var db = database.open()
119
                            if db != nil {
120
                                var sync = SyncModel()
121
                                sync.data = token
122
                                sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
123
 
124
                                let syncDao = SyncDao(db: db)
125
 
126
                                if syncDao.insert(record: sync) > 0 {
127
 
128
                                    appData.fcmToken = token
129
                                    appData.save()
130
 
131
                                    syncAdapter.sync {
132
                                            success in
133
                                    }
134
                                }
135
                            }
136
                            database.close()
137
 
138
 
139
 
140
 
141
                        }
142
                   }
143
               }
144
           }
145
        }
146
 
1 efrain 147
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
148
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
149
 
150
        if let messageID = userInfo[gcmMessageIDKey] {
151
            print("Message ID: \(messageID)")
152
        }
153
 
154
 
155
        processNotification(userInfo: userInfo, isForeground: false)
156
        completionHandler(UIBackgroundFetchResult.newData)
157
    }
158
 
12 efrain 159
    func registerBGTasksScheduler() {
160
        BGTaskScheduler.shared.register(forTaskWithIdentifier: Constants.BACKGROUND_TASK_REFRESH, using: nil) { task in
161
                 self.handleRefreshTask(task: task as! BGAppRefreshTask)
162
        }
163
 
164
        BGTaskScheduler.shared.register(forTaskWithIdentifier: Constants.BACKGROUND_TASK_PROCESS, using: nil) { task in
165
                 self.handleProcessTask(task: task as! BGProcessingTask)
166
        }
1 efrain 167
 
12 efrain 168
    }
169
 
170
    func scheduleRefresh() {
171
        let request = BGAppRefreshTaskRequest(identifier: Constants.BACKGROUND_TASK_REFRESH)
172
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
173
 
174
 
175
 
176
        do {
177
             try BGTaskScheduler.shared.submit(request)
178
        } catch {
179
            print("Could not schedule app refresh: \(error)")
180
        }
181
    }
182
 
183
    func scheduleProcess() {
184
        let request = BGProcessingTaskRequest(identifier: Constants.BACKGROUND_TASK_PROCESS)
185
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
186
        request.requiresNetworkConnectivity = true
187
        request.requiresExternalPower = false
188
 
189
        do {
190
            try BGTaskScheduler.shared.submit(request)
191
        } catch {
192
            print("Could not schedule processing: \(error)")
193
        }
194
    }
195
 
196
    func handleProcessTask(task: BGProcessingTask) {
197
        scheduleProcess()
198
 
199
        let syncAdapter = SyncAdapter()
15 efrain 200
        syncAdapter.sync(isForeground: false) { success in
12 efrain 201
            task.setTaskCompleted(success: success)
202
        }
203
 
204
        task.setTaskCompleted(success: true)
205
    }
206
 
207
    func handleRefreshTask(task: BGAppRefreshTask) {
208
        scheduleRefresh()
209
 
210
 
211
 
212
        let syncAdapter = SyncAdapter()
213
        if syncAdapter.isCheckChangesRequired() {
214
            syncAdapter.checkChanges(isForeground: false) { success in
215
                task.setTaskCompleted(success: success)
216
            }
217
        } else {
218
            task.expirationHandler = {
219
                task.setTaskCompleted(success: false)
220
             }
221
        }
222
 
223
 
224
        task.setTaskCompleted(success: true)
225
    }
1 efrain 226
 
12 efrain 227
 
228
 
1 efrain 229
}
230
 
231
extension AppDelegate: MessagingDelegate {
232
 
233
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
234
 
15 efrain 235
 
1 efrain 236
        let token = fcmToken ?? ""
15 efrain 237
        print( "MessagingDelegate didReceiveRegistrationToken: \(token)")
1 efrain 238
 
15 efrain 239
        let userInfo = ["token": token]
240
           NotificationCenter.default.post(name: .receivingNewToken , object: self, userInfo: userInfo)
241
 
1 efrain 242
 
15 efrain 243
 
1 efrain 244
    }
245
}
246
 
247
@available(iOS 10, *)
248
extension AppDelegate : UNUserNotificationCenterDelegate {
249
 
250
  // Receive displayed notifications for iOS 10 devices.
251
  func userNotificationCenter(_ center: UNUserNotificationCenter,
252
                              willPresent notification: UNNotification,
253
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
254
    let userInfo = notification.request.content.userInfo
255
 
256
    if let messageID = userInfo[gcmMessageIDKey] {
257
        print("Message ID: \(messageID)")
258
    }
259
 
260
    processNotification(userInfo: userInfo, isForeground: true)
261
    completionHandler([[.banner, .badge, .sound]])
262
  }
263
 
264
    private func processNotification(userInfo : [AnyHashable : Any], isForeground : Bool) {
265
        let now = Date()
266
        let dateFormatter = DateFormatter()
267
        dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
268
 
269
        let timeFormatter = DateFormatter()
270
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12
271
 
272
 
273
        guard let apsDict = userInfo["aps"]as?[String:Any] else {return}
274
        guard let alertDict = apsDict["alert"]as?[String:Any]else {return}
275
 
276
 
277
        let title = alertDict["title"]  as? String ?? ""
278
        let body = alertDict["body"]  as? String ?? ""
279
        let url = userInfo.index(forKey: "url")  == nil ?  "" : userInfo["url"] as? String ?? ""
280
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
281
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
282
 
283
 
284
        if command == "signout" {
285
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
286
        }
287
        else if command == "content-refresh" {
288
            let userinfo = [
289
                "title" : title,
290
                "body" : body,
291
                "new_capsules" : String(newCapsules),
292
                "is_foreground" : (isForeground ? "1" : "0")
293
            ]
294
 
295
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
296
        } else {
297
 
298
            let userinfo = [
299
                "title" : title,
300
                "body" : body,
301
                "url" : url,
302
            ]
303
 
304
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)
305
 
306
 
307
        }
308
    }
309
 
310
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
311
 
15 efrain 312
        print( "didRegisterForRemoteNotificationsWithDeviceToken")
1 efrain 313
 
15 efrain 314
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
315
        let token = tokenParts.joined()
1 efrain 316
            print("token: ", token)
15 efrain 317
 
1 efrain 318
 
15 efrain 319
        let userInfo = ["token": token]
320
        NotificationCenter.default.post(name: .receivingNewToken , object: self, userInfo: userInfo)
321
 
1 efrain 322
    }
323
 
324
 
325
 
326
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
327
        print( "didFailToRegisterForRemoteNotificationsWithError")
328
    }
329
 
330
  func userNotificationCenter(_ center: UNUserNotificationCenter,
331
                              didReceive response: UNNotificationResponse,
332
                              withCompletionHandler completionHandler: @escaping () -> Void) {
333
    let userInfo = response.notification.request.content.userInfo
334
 
335
    if let messageID = userInfo[gcmMessageIDKey] {
336
      print("Message ID from userNotificationCenter didReceive: \(messageID)")
337
    }
338
 
339
 
340
    processNotification(userInfo: userInfo, isForeground: true)
341
 
342
    completionHandler()
343
  }
344
}