Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

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