Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

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