Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

Rev 44 | Rev 58 | 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
45 efrain 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
 
45 efrain 157
 
24 efrain 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 ?? ""
44 efrain 172
        let url = userInfo.index(forKey: "url")  == nil ?  "" : userInfo["url"] as? String ?? ""
173
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
43 efrain 174
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
44 efrain 175
 
176
 
17 efrain 177
        if command == "signout" {
39 efrain 178
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
32 efrain 179
        }
44 efrain 180
        else if command == "content-refresh" {
32 efrain 181
            let userinfo = [
27 efrain 182
                "title" : title,
183
                "body" : body,
184
                "new_capsules" : String(newCapsules),
185
                "is_foreground" : (isForeground ? "1" : "0")
186
            ]
17 efrain 187
 
188
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
27 efrain 189
        } else {
8 efrain 190
 
27 efrain 191
            let userinfo = [
192
                "title" : title,
193
                "body" : body,
194
                "url" : url,
195
            ]
8 efrain 196
 
31 efrain 197
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)
25 efrain 198
 
23 efrain 199
 
17 efrain 200
        }
201
    }
202
 
203
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
204
 
205
            print( "didRegisterForRemoteNotificationsWithDeviceToken")
8 efrain 206
 
17 efrain 207
            let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
208
            let token = tokenParts.joined()
209
            print("token: ", token)
210
 
211
 
212
           if appData.fcmToken != token  {
213
 
214
               var sync = SyncModel()
215
               sync.data = token
216
               sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
217
 
218
               if SyncDao.sharedInstance.insert(record: sync) > 0 {
219
 
220
                   appData.fcmToken = token
221
                   appData.save()
222
 
223
                   syncAdapter.sync {
224
                           success in
225
                   }
226
               }
8 efrain 227
           }
228
    }
229
 
230
 
231
 
17 efrain 232
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
233
        print( "didFailToRegisterForRemoteNotificationsWithError")
234
    }
8 efrain 235
 
1 efrain 236
  func userNotificationCenter(_ center: UNUserNotificationCenter,
237
                              didReceive response: UNNotificationResponse,
238
                              withCompletionHandler completionHandler: @escaping () -> Void) {
17 efrain 239
    let userInfo = response.notification.request.content.userInfo
240
 
241
    if let messageID = userInfo[gcmMessageIDKey] {
242
      print("Message ID from userNotificationCenter didReceive: \(messageID)")
243
    }
1 efrain 244
 
245
 
17 efrain 246
    processNotification(userInfo: userInfo, isForeground: true)
1 efrain 247
 
248
    completionHandler()
249
  }
250
}