Proyectos de Subversion Iphone Microlearning - Nuevo Interface

Rev

Rev 59 | Ir a la última revisión | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 59 Rev 61
Línea 7... Línea 7...
7
 
7
 
8
import Foundation
8
import Foundation
9
import Firebase
9
import Firebase
10
import Messages
10
import Messages
-
 
11
import BackgroundTasks
Línea 11... Línea 12...
11
import BackgroundTasks
12
import SwiftUI
Línea 12... Línea -...
12
 
-
 
13
//UIResponder, UIApplicationDelegate {
-
 
14
 
-
 
15
class SyncForegroundObservableObject: ObservableObject
-
 
16
{
-
 
17
    @Published var timer : Timer = Timer()
13
 
18
}
-
 
19
 
-
 
-
 
14
//UIResponder, UIApplicationDelegate {
20
class AppDelegate : NSObject, UIApplicationDelegate {
15
 
21
    private var isSyncInProgress = false
16
class AppDelegate : NSObject, UIApplicationDelegate {
-
 
17
 
-
 
18
    private let gcmMessageIDKey = "gcm.message_id"
Línea 22... Línea 19...
22
    private var syncAdapter = SyncAdapter()
19
    private var appData = AppData.sharedInstance
23
    private let gcmMessageIDKey = "gcm.message_id"
-
 
24
    private var appData = AppData.sharedInstance
-
 
25
 
20
    public static var orientationLock = UIInterfaceOrientationMask.portrait
26
 
21
    
27
    static var orientationLock = UIInterfaceOrientationMask.portrait
22
 
Línea 28... Línea 23...
28
 
23
    
29
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
24
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
Línea 30... Línea 25...
30
        return AppDelegate.orientationLock
25
        return AppDelegate.orientationLock
31
    }
26
    }
32
    
27
    
33
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
28
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
Línea 34... Línea -...
34
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
-
 
35
 
-
 
36
        let database = Database.sharedInstance
-
 
37
        if database.open() != nil {
-
 
38
              database.createTables()
-
 
39
        }
-
 
40
        
29
        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
41
        if let new_uuid = UIDevice.current.identifierForVendor?.uuidString {
30
 
42
           
-
 
43
            let old_uuid = appData.deviceUuid
-
 
44
            if new_uuid != old_uuid {
31
        /*        let database = Database.sharedInstance
45
                var sync = SyncModel()
-
 
46
                sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
32
        if database.open() != nil  {
47
                sync.data = new_uuid
33
            database.createTables()
48
                
34
        }
49
                if SyncDao.sharedInstance.insert(record: sync) > 0 {
-
 
50
                    appData.deviceUuid = new_uuid
35
        
-
 
36
        */
-
 
37
        
-
 
38
        /*
-
 
39
        for  fontFamily in  UIFont.familyNames {
Línea -... Línea 40...
-
 
40
            for fontName in UIFont.fontNames(forFamilyName: fontFamily) {
-
 
41
                print("\(fontName)")
51
                    appData.save()
42
            }
-
 
43
        }*/
-
 
44
        
-
 
45
    /*        print("observador del UUID del dispositivo")
-
 
46
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewDevice(n:)), name: Constants.NOTIFICATION_NAME_DEVICE_REGISTER_NAME, object: nil)
Línea 52... Línea 47...
52
                    
47
 
Línea 53... Línea 48...
53
                    syncAdapter.sync {
48
        print("observador del FCM TOKEN")
Línea 54... Línea 49...
54
                            success in
49
        NotificationCenter.default.addObserver(self, selector: #selector(receivingNewToken(n:)), name: Constants.NOTIFICATION_NAME_FCM_REGISTER_NAME, object: nil)
55
                    }
50
        */
56
                }
51
        
57
            }
52
        
58
 
53
        
59
        }
54
        
60
              
55
              
61
  
56
  
62
        FirebaseApp.configure()
57
        FirebaseApp.configure()
63
 
58
 
64
                Messaging.messaging().delegate = self
59
        Messaging.messaging().delegate = self
65
 
60
 
66
                if #available(iOS 10.0, *) {
61
        if #available(iOS 10.0, *) {
Línea 67... Línea 62...
67
                  // For iOS 10 display notification (sent via APNS)
62
            // For iOS 10 display notification (sent via APNS)
Línea -... Línea 63...
-
 
63
            UNUserNotificationCenter.current().delegate = self
-
 
64
 
68
                  UNUserNotificationCenter.current().delegate = self
65
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
69
 
66
            UNUserNotificationCenter.current().requestAuthorization(
70
                  let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
67
                options: authOptions,
Línea 71... Línea 68...
71
                  UNUserNotificationCenter.current().requestAuthorization(
68
                completionHandler: {_, _ in })
72
                    options: authOptions,
69
        } else {
Línea -... Línea 70...
-
 
70
            let settings: UIUserNotificationSettings =
-
 
71
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
-
 
72
            application.registerUserNotificationSettings(settings)
-
 
73
        }
-
 
74
 
-
 
75
        application.registerForRemoteNotifications()
-
 
76
        
-
 
77
        
-
 
78
        
-
 
79
        registerBGTasksScheduler()
-
 
80
        scheduleProcess()
-
 
81
        scheduleRefresh()
-
 
82
        
-
 
83
        return true
-
 
84
    }
-
 
85
    
-
 
86
    // Storage of the UID once the notification is received
-
 
87
    /*
-
 
88
     @objc func receivingNewDevice(n: NSNotification){
-
 
89
 
-
 
90
            print("receivingNewDevice")
-
 
91
            if n.userInfo != nil{
-
 
92
                if let new_uuid = n.userInfo?["uuid"]! as? String {
-
 
93
                    let old_uuid = appData.deviceUuid
-
 
94
                    if new_uuid != old_uuid {
-
 
95
                        
-
 
96
                        var sync = SyncModel()
-
 
97
                        sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
-
 
98
                        sync.data = new_uuid
-
 
99
                            
-
 
100
                        let syncDao = SyncDao()
-
 
101
                        if syncDao.insert(record: sync) > 0 {
-
 
102
                            appData.deviceUuid = new_uuid
-
 
103
                            appData.save()
-
 
104
                                
-
 
105
                            syncAdapter.sync(isForeground: true) {
-
 
106
                                success in
-
 
107
                            }
-
 
108
                        }
-
 
109
                        
-
 
110
                    }
-
 
111
                }
-
 
112
            }
-
 
113
        }
-
 
114
           
-
 
115
        @objc func receivingNewToken(n: NSNotification){
-
 
116
            if n.userInfo != nil{
-
 
117
                if let token = n.userInfo?["token"]! as? String {
-
 
118
                    if !token.isEmpty {
-
 
119
                        if appData.fcmToken != token  {
-
 
120
                            
-
 
121
                            var sync = SyncModel()
-
 
122
                            sync.data = token
-
 
123
                            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
-
 
124
                                
-
 
125
                            let syncDao = SyncDao()
-
 
126
                            if syncDao.insert(record: sync) > 0 {
-
 
127
                                appData.fcmToken = token
-
 
128
                                appData.save()
-
 
129
                                    
-
 
130
                                syncAdapter.sync(isForeground: true) {
-
 
131
                                    success in
-
 
132
                                }
-
 
133
                            }
-
 
134
 
-
 
135
                        }
-
 
136
                   }
73
                    completionHandler: {_, _ in })
137
               }
-
 
138
           }
74
                } else {
139
        }*/
75
                  let settings: UIUserNotificationSettings =
140
    
76
                  UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
141
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
Línea 77... Línea 142...
77
                  application.registerUserNotificationSettings(settings)
142
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Línea 96... Línea 161...
96
        }
161
        }
Línea 97... Línea 162...
97
 
162
 
Línea 98... Línea 163...
98
    }
163
    }
-
 
164
        
99
        
165
    func scheduleRefresh() {
100
    func scheduleRefresh() {
166
        print("background: scheduleRefresh")
Línea 101... Línea 167...
101
        let request = BGAppRefreshTaskRequest(identifier: Constants.BACKGROUND_TASK_REFRESH)
167
        let request = BGAppRefreshTaskRequest(identifier: Constants.BACKGROUND_TASK_REFRESH)
102
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
168
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
103
        
169
        
104
 
170
 
105
            
171
            
106
        do {
172
        do {
Línea 107... Línea 173...
107
             try BGTaskScheduler.shared.submit(request)
173
             try BGTaskScheduler.shared.submit(request)
-
 
174
        } catch {
108
        } catch {
175
            print("background: Could not schedule app refresh: \(error)")
109
            print("Could not schedule app refresh: \(error)")
176
        }
110
        }
177
    }
111
    }
178
        
Línea 112... Línea 179...
112
        
179
    func scheduleProcess() {
113
    func scheduleProcess() {
180
        print("background: scheduleProcess")
114
        let request = BGProcessingTaskRequest(identifier: Constants.BACKGROUND_TASK_PROCESS)
181
        let request = BGProcessingTaskRequest(identifier: Constants.BACKGROUND_TASK_PROCESS)
115
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
182
        request.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)
116
        request.requiresNetworkConnectivity = true
183
        request.requiresNetworkConnectivity = true
117
        request.requiresExternalPower = false
184
        request.requiresExternalPower = false
Línea 118... Línea 185...
118
 
185
 
119
        do {
186
        do {
-
 
187
            try BGTaskScheduler.shared.submit(request)
Línea 120... Línea 188...
120
            try BGTaskScheduler.shared.submit(request)
188
        } catch {
121
        } catch {
189
            print("background: Could not schedule processing: \(error)")
122
            print("Could not schedule processing: \(error)")
190
        }
123
        }
191
    }
Línea 124... Línea -...
124
    }
-
 
125
        
-
 
126
    func handleProcessTask(task: BGProcessingTask) {
-
 
127
        scheduleProcess()
-
 
128
        
-
 
129
        let syncAdapter = SyncAdapter()
192
        
130
        syncAdapter.sync { success in
193
    func handleProcessTask(task: BGProcessingTask) {
Línea 131... Línea 194...
131
            task.setTaskCompleted(success: success)
194
        scheduleProcess()
132
        }
195
        print("background: handleProcessTask")
Línea 133... Línea -...
133
 
-
 
-
 
196
        
Línea 134... Línea 197...
134
        /*
197
        let syncAdapter = SyncAdapter()
135
        task.expirationHandler = {
198
        syncAdapter.sync(isForeground: false) { success in
136
            task.setTaskCompleted(success: false)
199
            task.setTaskCompleted(success: success)
137
         }
200
        }
Línea 157... Línea 220...
157
        
220
        
158
 
221
 
Línea 159... Línea -...
159
        task.setTaskCompleted(success: true)
-
 
160
    }
-
 
161
    
-
 
162
    
-
 
163
    
-
 
164
    
-
 
165
    
-
 
166
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
-
 
167
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
-
 
168
 
-
 
169
        if let messageID = userInfo[gcmMessageIDKey] {
-
 
170
            print("Message ID: \(messageID)")
-
 
171
        }
-
 
172
        
-
 
173
 
-
 
174
        processNotification(userInfo: userInfo, isForeground: false)
-
 
Línea 175... Línea 222...
175
        completionHandler(UIBackgroundFetchResult.newData)
222
        task.setTaskCompleted(success: true)
Línea 176... Línea 223...
176
    }
223
    }
Línea 177... Línea 224...
177
    
224
    
Línea -... Línea 225...
-
 
225
 
178
 
226
    
-
 
227
}
-
 
228
 
179
    
229
extension AppDelegate: MessagingDelegate {
-
 
230
    
Línea 180... Línea -...
180
}
-
 
181
 
231
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
182
extension AppDelegate: MessagingDelegate {
-
 
183
    
-
 
184
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
-
 
185
 
-
 
186
        let token = fcmToken ?? ""
-
 
187
        print("token: ", token)
-
 
188
        
-
 
189
 
-
 
190
        if appData.fcmToken != token  {
-
 
191
            
-
 
192
            var sync = SyncModel()
-
 
193
            sync.data = token
-
 
194
            sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
-
 
195
            
-
 
196
            if SyncDao.sharedInstance.insert(record: sync) > 0 {
232
 
197
            
233
  
Línea 198... Línea 234...
198
                appData.fcmToken = token
234
        let token = fcmToken ?? ""
199
                appData.save()
235
        print( "MessagingDelegate didReceiveRegistrationToken: \(token)")
Línea 228... Línea 264...
228
        let dateFormatter = DateFormatter()
264
        let dateFormatter = DateFormatter()
229
        dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
265
        dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
Línea 230... Línea 266...
230
        
266
        
231
        let timeFormatter = DateFormatter()
267
        let timeFormatter = DateFormatter()
232
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12
-
 
233
        /*
-
 
234
        let dateOn = dateFormatter.string(from: now)
-
 
235
        let timeOn = dateFormatter.string(from: now)
-
 
236
        
-
 
237
        let userNotificationDao = UserNotificationDao.sharedInstance
-
 
238
        var userNotification : UserNotificationModel
-
 
239
        
-
 
240
   
-
 
241
        if Config.DEBUG && !appData.userUuid.isEmpty {
-
 
242
            userNotification = UserNotificationModel(userUuid: appData.userUuid, title: "userInfo", body: "\(userInfo)", viewed: 0, url: "", dateOn: dateOn, timeOn: timeOn)
-
 
Línea 243... Línea -...
243
            
-
 
244
 
-
 
245
            userNotificationDao.insert(userNotification: userNotification)
-
 
Línea 246... Línea 268...
246
        }
268
        timeFormatter.dateFormat = Constants.FORMAT_TIME_12
247
         */
269
 
Línea 256... Línea 278...
256
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
278
        let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
257
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
279
        let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
Línea 258... Línea 280...
258
 
280
 
-
 
281
    
-
 
282
        if command == "signout" {
-
 
283
            let userinfo = [
-
 
284
                "is_foreground" : (isForeground ? "1" : "0")
259
    
285
            ]
260
        if command == "signout" {
286
            
261
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
287
            NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: userinfo)
262
        }
288
        }
263
        else if command == "content-refresh" {
289
        else if command == "content-refresh" {
264
            let userinfo = [
290
            let userinfo = [
Línea 283... Línea 309...
283
        }
309
        }
284
    }
310
    }
Línea 285... Línea 311...
285
 
311
 
Línea 286... Línea 312...
286
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
312
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Línea -... Línea 313...
-
 
313
 
-
 
314
        print( "didRegisterForRemoteNotificationsWithDeviceToken")
287
 
315
        
288
            print( "didRegisterForRemoteNotificationsWithDeviceToken")
316
    
289
        
317
        
-
 
318
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
290
            let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
319
        let token = tokenParts.joined()
-
 
320
            print("token: ", token)
-
 
321
        
Línea 291... Línea -...
291
            let token = tokenParts.joined()
-
 
292
            print("token: ", token)
-
 
293
           
-
 
294
 
-
 
295
           if appData.fcmToken != token  {
-
 
296
               
-
 
297
               var sync = SyncModel()
-
 
298
               sync.data = token
-
 
299
               sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
-
 
300
               
-
 
301
               if SyncDao.sharedInstance.insert(record: sync) > 0 {
-
 
302
               
-
 
303
                   appData.fcmToken = token
-
 
304
                   appData.save()
-
 
305
                   
-
 
306
                   syncAdapter.sync {
-
 
307
                           success in
322
 
Línea 308... Línea 323...
308
                   }
323
        let userInfo = ["token": token]