Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

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