Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 1 | Rev 12 | 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()
76
                return true
77
 
78
 
79
 
80
 
81
    }
82
 
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
    }
94
 
95
 
96
 
97
}
98
 
99
extension AppDelegate: MessagingDelegate {
100
 
101
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
102
 
103
        let token = fcmToken ?? ""
104
        print("token: ", token)
105
 
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
120
                }
121
            }
122
        }
123
    }
124
}
125
 
126
@available(iOS 10, *)
127
extension AppDelegate : UNUserNotificationCenterDelegate {
128
 
129
  // Receive displayed notifications for iOS 10 devices.
130
  func userNotificationCenter(_ center: UNUserNotificationCenter,
131
                              willPresent notification: UNNotification,
132
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
133
    let userInfo = notification.request.content.userInfo
134
 
135
    if let messageID = userInfo[gcmMessageIDKey] {
136
        print("Message ID: \(messageID)")
137
    }
138
 
139
    processNotification(userInfo: userInfo, isForeground: true)
140
    completionHandler([[.banner, .badge, .sound]])
141
  }
142
 
143
    private func processNotification(userInfo : [AnyHashable : Any], isForeground : Bool) {
144
        let now = Date()
145
        let dateFormatter = DateFormatter()
146
        dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
147
 
148
        let timeFormatter = DateFormatter()
149
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12
2 efrain 150
        /*
1 efrain 151
        let dateOn = dateFormatter.string(from: now)
152
        let timeOn = dateFormatter.string(from: now)
153
 
154
        let userNotificationDao = UserNotificationDao.sharedInstance
155
        var userNotification : UserNotificationModel
156
 
2 efrain 157
 
1 efrain 158
        if Config.DEBUG && !appData.userUuid.isEmpty {
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
        }
164
         */
165
 
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 ?? ""
172
        let url = userInfo.index(forKey: "url")  == nil ?  "" : userInfo["url"] as? String ?? ""
173
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
174
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
175
 
176
 
177
        if command == "signout" {
178
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
179
        }
180
        else if command == "content-refresh" {
181
            let userinfo = [
182
                "title" : title,
183
                "body" : body,
184
                "new_capsules" : String(newCapsules),
185
                "is_foreground" : (isForeground ? "1" : "0")
186
            ]
187
 
188
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
189
        } else {
190
 
191
            let userinfo = [
192
                "title" : title,
193
                "body" : body,
194
                "url" : url,
195
            ]
196
 
197
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)
198
 
199
 
200
        }
201
    }
202
 
203
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
204
 
205
            print( "didRegisterForRemoteNotificationsWithDeviceToken")
206
 
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
               }
227
           }
228
    }
229
 
230
 
231
 
232
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
233
        print( "didFailToRegisterForRemoteNotificationsWithError")
234
    }
235
 
236
  func userNotificationCenter(_ center: UNUserNotificationCenter,
237
                              didReceive response: UNNotificationResponse,
238
                              withCompletionHandler completionHandler: @escaping () -> Void) {
239
    let userInfo = response.notification.request.content.userInfo
240
 
241
    if let messageID = userInfo[gcmMessageIDKey] {
242
      print("Message ID from userNotificationCenter didReceive: \(messageID)")
243
    }
244
 
245
 
246
    processNotification(userInfo: userInfo, isForeground: true)
247
 
248
    completionHandler()
249
  }
250
}