Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

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