Skip to content

Instantly share code, notes, and snippets.

@nhatduong
Created May 13, 2022 10:02
Show Gist options
  • Select an option

  • Save nhatduong/a15724e9c00a240ddce5b82b5da35612 to your computer and use it in GitHub Desktop.

Select an option

Save nhatduong/a15724e9c00a240ddce5b82b5da35612 to your computer and use it in GitHub Desktop.
import UIKit
import GoogleMaps
import FBSDKCoreKit
import FBSDKLoginKit
import UserNotifications
import Firebase
import FirebaseMessaging
import GoogleSignIn
//import TwitterKit
//import SwifteriOS
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// print(UserModel.getUserInfo())
if !UserModel.getUserInfo().isSaveLoginApp {
UserModel.destroyUserInfo()
}
let dataGoogleConfig = getDataInInfoPlist(withName: "GoogleService-Info")
let dataTwitterConfig = getDataInInfoPlist(withName: "TwitterConfig")
// UserModel.setUserInfo(userData: ["token": ""])
//ProvideAPIKey = "AIzaSyCNOZD9ppLY2tpAhUTjQT4nFBOVCa6aep4"
appVar.lifecycleApp = "didFinishLaunchingWithOptions"
GMSServices.provideAPIKey(dataGoogleConfig["ProvideAPIKey"] as! String)
ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
// print("dataGoogleFirebase", dataGoogleFirebase, dataGoogleFirebase["CLIENT_ID"] as! String)
AppConfigModel.setData(configData: ["keyGoogleMap" : dataGoogleConfig["ProvideAPIKey"] as! String,
"linkSharePost" : Endpoint.linkShare,
"linkInvite": "https://download..com",
"googleClient": dataGoogleConfig["CLIENT_ID"] as! String,
"twitterConsumerKey": dataTwitterConfig["TwitterConsumerKey"] as! String,
"twitterConsumerSecret": dataTwitterConfig["TwitterConsumerSecret"] as! String])
FirebaseApp.configure()
Messaging.messaging().delegate = self
configApplePush(application)
// let center = UNUserNotificationCenter.current()
// center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// // Enable or disable features based on authorization.
// }
// application.registerForRemoteNotifications()
handleNotificationWhenAppIsKilled(launchOptions)
startApp()
return true
}
func configApplePush(_ application: UIApplication) {
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()
if let token = Messaging.messaging().fcmToken {
print("FCM token: \(token)")
appVar.tokenDevice = token
if UserModel.getUserInfo().isSaveLoginApp {
DispatchQueue.main.async {
Login.shared.saveTokenPush(token: appVar.tokenDevice)
}
}
}
}
@available(iOS 9.0, *)
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
if appVar.loginSocialType == "GOOGLE" {
return GIDSignIn.sharedInstance.handle(url)
}
// print("url", url)
if appVar.loginSocialType == "TWITTERAPP" {
let urlFormat = URL(string: url.absoluteString.replacingOccurrences(of: "-\(AppConfigModel.getData().twitterConsumerKey)", with: "").replacingOccurrences(of: "://", with: "://tw?"))
let token = urlFormat?.valueOf("token")
let secret = urlFormat?.valueOf("secret")
NotificationCenter
.default
.post(name: NSNotification.Name("loginTwitterAppCallBack"), object: nil, userInfo: ["token" : token,
"token_secret": secret])
return false
}
if appVar.loginSocialType == "TWITTER" {
if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let items = (urlComponents.queryItems)! as [NSURLQueryItem]
if (url.scheme == "loca") {
var oauth_verifier = ""
for queryItem in items {
if(queryItem.name == "oauth_verifier") {oauth_verifier = queryItem.value ?? ""}
}
// print("url.scheme oauth_verifier", oauth_verifier)
NotificationCenter.default.post(name: NSNotification.Name("loginTwitterCallBack"), object: nil, userInfo: ["oauth_verifier" : oauth_verifier])
}
}
return false
}
let dataConfig = getDataInInfoPlist(withName: "Info")
if url.absoluteString.contains("fb\(dataConfig["FacebookAppID"] as! String)") {
ApplicationDelegate.shared.application(
app,
open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
)
return false
}
if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
if urlComponents.string == "loca://share-post" {
return false
}
let items = (urlComponents.queryItems)! as [NSURLQueryItem]
if (url.scheme == "loca") {
var referral_code = ""
var post_oid = ""
var cmd = ""
var type = ""
var lang = ""
for queryItem in items {
if(queryItem.name == "post_oid") {post_oid = queryItem.value ?? ""}
if(queryItem.name == "referral_code") {referral_code = queryItem.value ?? ""}
if(queryItem.name == "cmd") {cmd = queryItem.value ?? ""}
if(queryItem.name == "type") {type = queryItem.value ?? ""}
if(queryItem.name == "lang") {lang = queryItem.value ?? ""}
}
appVar.openInFromUrlSchema = [
"referral_code" : referral_code,
"id" : post_oid,
"cmd" : cmd,
"type" : type,
"lang" : lang
]
if appVar.lifecycleApp != "didFinishLaunchingWithOptions" {
let tabBar = AppDelegate.window?.rootViewController as? UITabBarController
if tabBar?.selectedIndex == 2 {
NotificationCenter.default.post(name: NSNotification.Name("openDetailPost"), object: nil)
} else {
queueAfter(interval: 1.0) {
StartApp.shared.changeTab(viewVC: Profile(), indexTab: 2)
}
}
}
return false
}
}
return false
}
func applicationWillEnterForeground(_ application: UIApplication) {
appVar.lifecycleApp = "applicationWillEnterForeground"
if appVar.checkingInternet {
NotificationCenter.default.post(name: NSNotification.Name("checkingInternet"), object: nil)
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.post(name: NSNotification.Name("applicationDidBecomeActiveScreen"), object: nil)
NotificationCenter.default.post(name: NSNotification.Name("reloadItemInAR"), object: nil)
// Thực hiện việc copy link
if let textInclipboard = UIPasteboard.general.string {
if let dataDeeplink = URL(string: textInclipboard), textInclipboard.verifyUrl() {
if let referral_code = dataDeeplink.valueOf("referral_code") {
UserModel.setUserInfo(userData: ["referral_code" : referral_code])
}
if let cmd = dataDeeplink.valueOf("cmd") , appVar.openInFromUrlSchema?.count == 0 {
let post_oid = dataDeeplink.valueOf("post_oid")
let referral_code = dataDeeplink.valueOf("referral_code")
let type = dataDeeplink.valueOf("type")
let lang = dataDeeplink.valueOf("lang")
appVar.openInFromUrlSchema = [
"referral_code" : referral_code ?? "",
"id" : post_oid ?? "",
"cmd" : cmd,
"type" : type ?? "",
"lang" : lang ?? ""
]
if UserModel.getUserInfo().user_oid != "" && UserModel.getUserInfo().referral_code_update {
if appVar.lifecycleApp != "didFinishLaunchingWithOptions" {
let tabBar = AppDelegate.window?.rootViewController as? UITabBarController
if tabBar?.selectedIndex == 2 {
NotificationCenter.default.post(name: NSNotification.Name("openDetailPost"), object: nil)
return
}
// print("22222= StartApp.shared.changeTab(viewVC: Profile(), indexTab: 2)")
queueAfter(interval: 1.0) {
StartApp.shared.changeTab(viewVC: Profile(), indexTab: 2)
}
}
}
}
}
}
}
func handleNotificationWhenAppIsKilled(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
// Check if launched from the remote notification and application is close
if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {
if let aps = remoteNotification["aps"] as? NSDictionary {
StartApp.shared.changeTab(viewVC: NotifyViewController(), indexTab: 0)
appVar.aps = aps
if !appVar.receiveMsgData {
appVar.receiveMsgData = true
self._showPopupNotify(dataPush: aps)
}
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
print("deviceToken", deviceTokenString)
Messaging.messaging().apnsToken = deviceToken
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("fcmToken", fcmToken)
appVar.tokenDevice = fcmToken
if UserModel.getUserInfo().isSaveLoginApp {
DispatchQueue.main.async {
Login.shared.saveTokenPush(token: appVar.tokenDevice)
}
}
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("fcmToken", fcmToken)
appVar.tokenDevice = fcmToken
if UserModel.getUserInfo().isSaveLoginApp {
DispatchQueue.main.async {
Login.shared.saveTokenPush(token: appVar.tokenDevice)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("error", error)
}
//
// func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
//// print("UBSSGU9SG6", deviceTokenString, UserModel.getUserInfo().isSaveLogin)
//
// if UserModel.getUserInfo().isSaveLoginApp {
// DispatchQueue.main.async {
//// print("appVar.tokenDevice", appVar.tokenDevice)
// Login.shared.saveTokenPush(token: appVar.tokenDevice)
// }
// }
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment