Proyectos de Subversion Iphone Microlearning

Rev

| 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
    var isSyncInProgress = false
17
    var database = Database()
18
    var timer = Timer()
19
    var syncAdapter = SyncAdapter()
20
    let gcmMessageIDKey = "gcm.message_id"
21
 
22
 
23
 
24
    /*
25
 
26
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
27
        // Called when a new scene session is being created.
28
        // Use this method to select a configuration to create the new scene with.
29
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
30
    }
31
 
32
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
33
        // Called when the user discards a scene session.
34
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
35
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
36
    }
37
 
38
    */
39
 
40
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
41
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
42
 
43
 
44
        print("Creación de las tablas")
45
        if database.open() != nil {
46
            database.createTables()
47
        }
48
 
49
 
50
        print("registro del dispositivo")
51
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: .receivingNewDevice, object: nil)
52
 
53
        if let uuid = UIDevice.current.identifierForVendor?.uuidString {
54
            let userInfo = ["uuid": uuid]
55
            NotificationCenter.default.post(name: .receivingNewDevice , object: self, userInfo: userInfo)
56
        }
57
 
58
 
59
        print("Firebase configuracion")
60
        FirebaseApp.configure()
61
 
62
        print("Firebase Token")
63
 
64
        UNUserNotificationCenter.current().delegate = self
65
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
66
        UNUserNotificationCenter.current().requestAuthorization(
67
            options: authOptions,
68
            completionHandler: {_, _ in }
69
        )
70
 
71
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: .receivingNewToken, object: nil)
72
 
73
        // Remote Notification Enable// Use Firebase library to configure APIs
74
 
75
        application.registerForRemoteNotifications()
76
        Messaging.messaging().delegate = self
77
 
78
 
79
         //Timer temporal
80
         print("timer foreground")
81
         timer.invalidate()
82
         timer = Timer.scheduledTimer(timeInterval: 30.0, target: syncAdapter, selector: #selector(syncAdapter.updateTimer), userInfo: nil, repeats: true)
83
 
84
         print("register background task \(Constants.IDENTIFIER_BACKGROUND_PROCESS)")
85
         BGTaskScheduler.shared.register(
86
             forTaskWithIdentifier: Constants.IDENTIFIER_BACKGROUND_PROCESS,
87
           using: nil) { (task) in
88
             print("Task handler")
89
             self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
90
         }
91
 
92
 
93
 
94
 
95
        return true;
96
 
97
    }
98
 
99
    func handleAppRefreshTask(task: BGAppRefreshTask) {
100
        print("Handling task")
101
 
102
        let syncAdapter = SyncAdapter()
103
        syncAdapter.sync{ success in
104
            //self.inProgress = false;
105
        }
106
        scheduleBackgroundSyncExecute()
107
    }
108
 
109
    func scheduleBackgroundSyncExecute()
110
     {
111
        print("scheduleBackgroundSyncExecute")
112
        let syncTask = BGAppRefreshTaskRequest(identifier: Constants.IDENTIFIER_BACKGROUND_PROCESS)
113
        syncTask.earliestBeginDate = Date(timeIntervalSinceNow: 60)
114
        do {
115
          try BGTaskScheduler.shared.submit(syncTask)
116
          print("task scheduled")
117
        } catch {
118
          print("Unable to submit task: \(error.localizedDescription)")
119
        }
120
      }
121
 
122
    // Storage of the UID once the notification is received
123
    @objc func receivingNewDevice(n: NSNotification){
124
 
125
            print("receivingNewDevice")
126
            if n.userInfo != nil{
127
                if let new_uuid = n.userInfo?["uuid"]! as? String {
128
                    let preference = Preference.sharedInstance
129
                    let old_uuid = preference.deviceUuid
130
                    if new_uuid != old_uuid {
131
                        var sync = SyncModel()
132
                        sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
133
                        sync.data = new_uuid
134
 
135
                        if SyncDao().insert(record: sync) > 0 {
136
                            preference.deviceUuid = new_uuid
137
                            preference.save()
138
 
139
 
140
 
141
                            syncAdapter.sync {
142
                                    success in
143
                            }
144
                        }
145
                    }
146
                }
147
            }
148
        }
149
 
150
        @objc func receivingNewToken(n: NSNotification){
151
            if n.userInfo != nil{
152
                if let token = n.userInfo?["token"]! as? String {
153
                    if !token.isEmpty {
154
                        let preference = Preference.sharedInstance
155
                        if preference.fcmToken != token  {
156
 
157
                            var sync = SyncModel()
158
                            sync.data = token
159
                            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
160
 
161
                            if SyncDao().insert(record: sync) > 0 {
162
 
163
                                preference.fcmToken = token
164
                                preference.save()
165
 
166
                                syncAdapter.sync {
167
                                        success in
168
                                }
169
                            }
170
                        }
171
                    }
172
                }
173
            }
174
        }
175
}
176
 
177
//Recibir mensajes
178
@available(iOS 10, *)
179
extension AppDelegate: UNUserNotificationCenterDelegate {
180
  // Receive displayed notifications for iOS 10 devices.
181
  func userNotificationCenter(_ center: UNUserNotificationCenter,
182
                              willPresent notification: UNNotification,
183
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
184
                                -> Void) {
185
    let userInfo = notification.request.content.userInfo
186
 
187
    // With swizzling disabled you must let Messaging know about the message, for Analytics
188
    // Messaging.messaging().appDidReceiveMessage(userInfo)
189
 
190
    // ...
191
 
192
    // Print full message.
193
    print(userInfo)
194
 
195
    // Change this to your preferred presentation option
196
    completionHandler([[.alert, .sound]])
197
  }
198
 
199
  func userNotificationCenter(_ center: UNUserNotificationCenter,
200
                              didReceive response: UNNotificationResponse,
201
                              withCompletionHandler completionHandler: @escaping () -> Void) {
202
    let userInfo = response.notification.request.content.userInfo
203
 
204
    // ...
205
 
206
    // With swizzling disabled you must let Messaging know about the message, for Analytics
207
    // Messaging.messaging().appDidReceiveMessage(userInfo)
208
 
209
    // Print full message.
210
    //print(userInfo)
211
 
212
    completionHandler()
213
  }
214
}
215
 
216
 
217
 
218
 
219
extension AppDelegate: MessagingDelegate {
220
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
221
 
222
        Messaging.messaging().token { token, error in
223
            if let error = error {
224
                print("Error fetching FCM registration token: \(error)")
225
            } else if let token = token {
226
                let userInfo = ["token": token]
227
                NotificationCenter.default.post(name: .receivingNewToken , object: self, userInfo: userInfo)
228
                print("FCM REGISTRATION TOKEN: \(token)")
229
            }
230
        }
231
    }
232
}
233
 
234
 
235