Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

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