Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

Rev 45 | 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
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"
17 efrain 19
    private var appData = AppData.sharedInstance
1 efrain 20
 
17 efrain 21
 
1 efrain 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
 
11 efrain 31
        let database = Database.sharedInstance
32
        if database.open() != nil {
33
              database.createTables()
34
        }
1 efrain 35
 
17 efrain 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
            }
1 efrain 53
 
54
        }
55
 
17 efrain 56
 
1 efrain 57
        FirebaseApp.configure()
58
 
17 efrain 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()
58 efrain 76
 
77
 
78
        registerBGTasksScheduler()
79
        scheduleProcess()
80
        scheduleRefresh()
81
 
82
 
17 efrain 83
                return true
84
 
1 efrain 85
 
86
 
87
 
88
    }
89
 
58 efrain 90
 
91
 
92
 
93
 
94
 
17 efrain 95
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
96
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
97
 
98
        if let messageID = userInfo[gcmMessageIDKey] {
99
            print("Message ID: \(messageID)")
100
        }
101
 
102
 
103
        processNotification(userInfo: userInfo, isForeground: false)
104
        completionHandler(UIBackgroundFetchResult.newData)
105
    }
1 efrain 106
 
17 efrain 107
 
8 efrain 108
 
17 efrain 109
}
1 efrain 110
 
17 efrain 111
extension AppDelegate: MessagingDelegate {
112
 
113
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
1 efrain 114
 
17 efrain 115
        let token = fcmToken ?? ""
116
        print("token: ", token)
1 efrain 117
 
17 efrain 118
 
119
        if appData.fcmToken != token  {
120
 
121
            var sync = SyncModel()
122
            sync.data = token
123
            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
124
 
125
            if SyncDao.sharedInstance.insert(record: sync) > 0 {
126
 
127
                appData.fcmToken = token
128
                appData.save()
129
 
130
                syncAdapter.sync {
131
                        success in
1 efrain 132
                }
133
            }
134
        }
17 efrain 135
    }
1 efrain 136
}
137
 
138
@available(iOS 10, *)
17 efrain 139
extension AppDelegate : UNUserNotificationCenterDelegate {
140
 
1 efrain 141
  // Receive displayed notifications for iOS 10 devices.
142
  func userNotificationCenter(_ center: UNUserNotificationCenter,
143
                              willPresent notification: UNNotification,
17 efrain 144
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
145
    let userInfo = notification.request.content.userInfo
1 efrain 146
 
17 efrain 147
    if let messageID = userInfo[gcmMessageIDKey] {
148
        print("Message ID: \(messageID)")
149
    }
1 efrain 150
 
17 efrain 151
    processNotification(userInfo: userInfo, isForeground: true)
152
    completionHandler([[.banner, .badge, .sound]])
153
  }
8 efrain 154
 
17 efrain 155
    private func processNotification(userInfo : [AnyHashable : Any], isForeground : Bool) {
22 efrain 156
        let now = Date()
157
        let dateFormatter = DateFormatter()
23 efrain 158
        dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
159
 
160
        let timeFormatter = DateFormatter()
161
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12
45 efrain 162
        /*
22 efrain 163
        let dateOn = dateFormatter.string(from: now)
23 efrain 164
        let timeOn = dateFormatter.string(from: now)
165
 
166
        let userNotificationDao = UserNotificationDao.sharedInstance
167
        var userNotification : UserNotificationModel
168
 
45 efrain 169
 
24 efrain 170
        if Config.DEBUG && !appData.userUuid.isEmpty {
23 efrain 171
            userNotification = UserNotificationModel(userUuid: appData.userUuid, title: "userInfo", body: "\(userInfo)", viewed: 0, url: "", dateOn: dateOn, timeOn: timeOn)
172
 
173
 
174
            userNotificationDao.insert(userNotification: userNotification)
175
        }
24 efrain 176
         */
23 efrain 177
 
24 efrain 178
        guard let apsDict = userInfo["aps"]as?[String:Any] else {return}
179
        guard let alertDict = apsDict["alert"]as?[String:Any]else {return}
180
 
181
 
182
        let title = alertDict["title"]  as? String ?? ""
183
        let body = alertDict["body"]  as? String ?? ""
44 efrain 184
        let url = userInfo.index(forKey: "url")  == nil ?  "" : userInfo["url"] as? String ?? ""
185
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
43 efrain 186
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
44 efrain 187
 
188
 
17 efrain 189
        if command == "signout" {
39 efrain 190
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
32 efrain 191
        }
44 efrain 192
        else if command == "content-refresh" {
32 efrain 193
            let userinfo = [
27 efrain 194
                "title" : title,
195
                "body" : body,
196
                "new_capsules" : String(newCapsules),
197
                "is_foreground" : (isForeground ? "1" : "0")
198
            ]
17 efrain 199
 
200
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
27 efrain 201
        } else {
8 efrain 202
 
27 efrain 203
            let userinfo = [
204
                "title" : title,
205
                "body" : body,
206
                "url" : url,
207
            ]
8 efrain 208
 
31 efrain 209
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)
25 efrain 210
 
23 efrain 211
 
17 efrain 212
        }
213
    }
214
 
215
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
216
 
217
            print( "didRegisterForRemoteNotificationsWithDeviceToken")
8 efrain 218
 
17 efrain 219
            let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
220
            let token = tokenParts.joined()
221
            print("token: ", token)
222
 
223
 
224
           if appData.fcmToken != token  {
225
 
226
               var sync = SyncModel()
227
               sync.data = token
228
               sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
229
 
230
               if SyncDao.sharedInstance.insert(record: sync) > 0 {
231
 
232
                   appData.fcmToken = token
233
                   appData.save()
234
 
235
                   syncAdapter.sync {
236
                           success in
237
                   }
238
               }
8 efrain 239
           }
240
    }
241
 
242
 
243
 
17 efrain 244
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
245
        print( "didFailToRegisterForRemoteNotificationsWithError")
246
    }
8 efrain 247
 
1 efrain 248
  func userNotificationCenter(_ center: UNUserNotificationCenter,
249
                              didReceive response: UNNotificationResponse,
250
                              withCompletionHandler completionHandler: @escaping () -> Void) {
17 efrain 251
    let userInfo = response.notification.request.content.userInfo
252
 
253
    if let messageID = userInfo[gcmMessageIDKey] {
254
      print("Message ID from userNotificationCenter didReceive: \(messageID)")
255
    }
1 efrain 256
 
257
 
17 efrain 258
    processNotification(userInfo: userInfo, isForeground: true)
1 efrain 259
 
260
    completionHandler()
261
  }
262
}