Rev 2 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
//
// AppDelegate.swift
// twogetskills
//
// Created by Efrain Yanez Recanatini on 2/23/22.
//
import Foundation
import Firebase
import Messages
import BackgroundTasks
//UIResponder, UIApplicationDelegate {
class AppDelegate : NSObject, UIApplicationDelegate {
private var isSyncInProgress = false
private var syncAdapter = SyncAdapter()
private let gcmMessageIDKey = "gcm.message_id"
private var appData = AppData.sharedInstance
static var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let database = Database.sharedInstance
if database.open() != nil {
database.createTables()
}
if let new_uuid = UIDevice.current.identifierForVendor?.uuidString {
let old_uuid = appData.deviceUuid
if new_uuid != old_uuid {
var sync = SyncModel()
sync.type = Constants.SYNC_ADAPTER_TYPE_DEVICE
sync.data = new_uuid
if SyncDao.sharedInstance.insert(record: sync) > 0 {
appData.deviceUuid = new_uuid
appData.save()
syncAdapter.sync {
success in
}
}
}
}
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
processNotification(userInfo: userInfo, isForeground: false)
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let token = fcmToken ?? ""
print("token: ", token)
if appData.fcmToken != token {
var sync = SyncModel()
sync.data = token
sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
if SyncDao.sharedInstance.insert(record: sync) > 0 {
appData.fcmToken = token
appData.save()
syncAdapter.sync {
success in
}
}
}
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
processNotification(userInfo: userInfo, isForeground: true)
completionHandler([[.banner, .badge, .sound]])
}
private func processNotification(userInfo : [AnyHashable : Any], isForeground : Bool) {
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = Constants.FORMAT_DATE_YMD
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = Constants.FORMAT_TIME_12
let dateOn = dateFormatter.string(from: now)
let timeOn = dateFormatter.string(from: now)
let userNotificationDao = UserNotificationDao.sharedInstance
var userNotification : UserNotificationModel
/*
if Config.DEBUG && !appData.userUuid.isEmpty {
userNotification = UserNotificationModel(userUuid: appData.userUuid, title: "userInfo", body: "\(userInfo)", viewed: 0, url: "", dateOn: dateOn, timeOn: timeOn)
userNotificationDao.insert(userNotification: userNotification)
}
*/
guard let apsDict = userInfo["aps"]as?[String:Any] else {return}
guard let alertDict = apsDict["alert"]as?[String:Any]else {return}
let title = alertDict["title"] as? String ?? ""
let body = alertDict["body"] as? String ?? ""
let url = userInfo.index(forKey: "url") == nil ? "" : userInfo["url"] as? String ?? ""
let command = userInfo.index(forKey: "command") == nil ? "" : userInfo["command"] as? String ?? ""
let newCapsules = userInfo.index(forKey: "new_capsules") == nil ? 0 : Int(userInfo["new_capsules"] as? String ?? "") ?? 0
if command == "signout" {
NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_EXIT , object: self, userInfo: nil)
}
else if command == "content-refresh" {
let userinfo = [
"title" : title,
"body" : body,
"new_capsules" : String(newCapsules),
"is_foreground" : (isForeground ? "1" : "0")
]
NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_COMMAND_REFRESH_CONTENT , object: self, userInfo: userinfo)
} else {
let userinfo = [
"title" : title,
"body" : body,
"url" : url,
]
NotificationCenter.default.post(name: Constants.NOTIFICATION_NAME_PUSH , object: self, userInfo: userInfo)
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print( "didRegisterForRemoteNotificationsWithDeviceToken")
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("token: ", token)
if appData.fcmToken != token {
var sync = SyncModel()
sync.data = token
sync.type = Constants.SYNC_ADAPTER_TYPE_FCM
if SyncDao.sharedInstance.insert(record: sync) > 0 {
appData.fcmToken = token
appData.save()
syncAdapter.sync {
success in
}
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print( "didFailToRegisterForRemoteNotificationsWithError")
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID from userNotificationCenter didReceive: \(messageID)")
}
processNotification(userInfo: userInfo, isForeground: true)
completionHandler()
}
}