//
// AppDelegate.swift
//
import UIKit
import KakaoSDKCommon
import KakaoSDKAuth
import FirebaseCore
import FirebaseFirestore
import FirebaseMessaging
import AppsFlyerLib
import SwiftyBootpay
import FirebaseDynamicLinks
import AppTrackingTransparency
import AdSupport
import ChannelIOFront
import Alamofire
import SwiftyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ChannelIO.initialize(application)
KakaoSDK.initSDK(appKey: "----------------------")
FirebaseApp.configure()
Bootpay.sharedInstance.appLaunch(application_id: "--------------------)
Messaging.messaging().delegate = self
AppsFlyerLib.shared().appsFlyerDevKey = "-----------------------"
AppsFlyerLib.shared().appleAppID = "------------------"
AppsFlyerLib.shared().deepLinkDelegate = self
AppsFlyerLib.shared().delegate = self
#if DEBUG
AppsFlyerLib.shared().isDebug = true
#endif
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 })
application.registerForRemoteNotifications()
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
// window = UIWindow(frame: UIScreen.main.bounds)
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// let view = storyboard.instantiateViewController(withIdentifier: "ViewController")
// let rootview = UINavigationController(rootViewController: view)
// window!.rootViewController = rootview
// window!.makeKeyAndVisible()
if(UserDefaults.standard.integer(forKey: UserDefaultsKey.lastBranch) == 0){
UserDefaults.standard.set(2, forKey: UserDefaultsKey.lastBranch)
}
Thread.sleep(forTimeInterval: 2.0)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
Bootpay.sharedInstance.sessionActive(active: false)
}
func applicationDidBecomeActive(_ application: UIApplication) {
AppsFlyerLib.shared().start()
Bootpay.sharedInstance.sessionActive(active: true)
let notificationName = Notification.Name("BecomeActive")
NotificationCenter.default.post(name: notificationName, object: nil)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
AppsFlyerLib.shared().continue(userActivity, restorationHandler: nil)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// print("APNs token retrieved: \(deviceToken)")
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
}
// print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
AppsFlyerLib.shared().handlePushNotification(userInfo)
if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
}
// Print full message.
// print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
AppsFlyerLib.shared().continue(userActivity, restorationHandler: nil)
let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
if let dynamiclink = dynamiclink {
if dynamiclink.url?.relativePath == "/invite" {
let notificationName = Notification.Name("RcvDeepLink")
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: [
"shortUrl" : userActivity.webpageURL!.absoluteString,
"inviteUrl": dynamiclink.url!.absoluteString
])
}
}
}
return handled
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if (AuthApi.isKakaoTalkLoginUrl(url)) {
return AuthController.handleOpenUrl(url: url)
}
return false
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
AppsFlyerLib.shared().handleOpen(url, sourceApplication: sourceApplication, withAnnotation: annotation)
return true
}
}
// [START ios_10_message_handling]
@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)")
}
// print(userInfo)
completionHandler([[.alert, .sound]])
}
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: \(messageID)")
}
// print(userInfo)
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
// print("Firebase registration token: \(String(describing: fcmToken))")
if let token = fcmToken {
let dataDict:[String: String] = ["token": token]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
// [END refresh_token]
}
extension AppDelegate: AppsFlyerLibDelegate {
// Handle Organic/Non-organic installation
func onConversionDataSuccess(_ data: [AnyHashable: Any]) {
// print("onConversionDataSuccess data:")
for (key, value) in data {
// print(key, ":", value)
}
if let status = data["af_status"] as? String {
if (status == "Non-organic") {
if let sourceID = data["media_source"],
let campaign = data["campaign"] {
// print("This is a Non-Organic install. Media source: \(sourceID) Campaign: \(campaign)")
}
} else {
// print("This is an organic install.")
}
if let is_first_launch = data["is_first_launch"] as? Bool,
is_first_launch {
// print("First Launch")
} else {
// print("Not First Launch")
}
}
}
func onConversionDataFail(_ error: Error) {
// print("\(error)")
}
// Handle Deeplink
func onAppOpenAttribution(_ attributionData: [AnyHashable: Any]) {
//Handle Deep Link Data
// print("onAppOpenAttribution data:")
for (key, value) in attributionData {
// print(key, ":",value)
}
}
func onAppOpenAttributionFailure(_ error: Error) {
// print("\(error)")
}
}
extension UIApplication {
/*function will return reference to tabbarcontroller */
func tabbarController() -> UIViewController? {
guard let vcs = self.keyWindow?.rootViewController?.children else { return nil }
for vc in vcs {
if let _ = vc as? UITabBarController {
return vc
}
}
return nil
}
}
extension AppDelegate: DeepLinkDelegate {
func didResolveDeepLink(_ result: DeepLinkResult) {
var fruitNameStr: String?
switch result.status {
case .notFound:
NSLog("[AFSDK] Deep link not found")
return
case .failure:
print("Error %@", result.error!)
return
case .found:
NSLog("[AFSDK] Deep link found")
}
guard let deepLinkObj:DeepLink = result.deepLink else {
NSLog("[AFSDK] Could not extract deep link object")
return
}
if deepLinkObj.clickEvent.keys.contains("deep_link_sub2") {
let ReferrerId:String = deepLinkObj.clickEvent["deep_link_sub2"] as! String
NSLog("[AFSDK] AppsFlyer: Referrer ID: \(ReferrerId)")
} else {
NSLog("[AFSDK] Could not extract referrerId")
}
let deepLinkStr:String = deepLinkObj.toString()
NSLog("[AFSDK] DeepLink data is: \(deepLinkStr)")
if( deepLinkObj.isDeferred == true) {
NSLog("[AFSDK] This is a deferred deep link")
}
else {
NSLog("[AFSDK] This is a direct deep link")
}
fruitNameStr = deepLinkObj.deeplinkValue
}
}
================= 로그인 버튼 코드 =================
if (UserApi.isKakaoTalkLoginAvailable()) {
UserApi.shared.loginWithKakaoTalk {(oauthToken, error) in
if let error = error {
print(error)
self.view.makeToast("카카오톡이 설치 되어있지 않거나 사용자가 로그인을 취소하였습니다.")
}
else {
self.kakaoUserInfo()
}
}
} else {
UserApi.shared.loginWithKakaoAccount {(oauthToken, error) in
if let error = error {
print(error)
self.view.makeToast("사용자가 로그인을 취소하였습니다.")
}
else {
self.kakaoUserInfo()
}
}
}
appdelegate와 로그인버튼 누를때 코드 입니다.