summaryrefslogtreecommitdiff
path: root/Juick/AppDelegate.swift
blob: d1062f4e590a513e617c24353ed7d557e23096ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
//
//  AppDelegate.swift
//  tst
//
//  Created by Vitaly Takmazov on 10.12.2019.
//  Copyright © 2019 com.juick. All rights reserved.
//

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    lazy var api : API = {
        return API()
    }()
    lazy var sharedDateFormatter : DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // cleanup synchronized credentials which are not used anymore
        let allCreds = URLCredentialStorage.shared.allCredentials
        for (space, _) in allCreds {
            if space.host == "api.juick.com" {
                allCreds[space]?.values.forEach {
                    URLCredentialStorage.shared.remove($0, for: space, options: [NSURLCredentialStorageRemoveSynchronizableCredentials:true])
                }
            }
        }
        #if !targetEnvironment(simulator)
        registerForRemoteNotifications()
        #endif
        if let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] {
            parseNotificationPayload(userInfo: userInfo as! [AnyHashable : Any])
        }
        return true
    }
    
    func registerForRemoteNotifications() {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if (error == nil) {
                OperationQueue.main.addOperation {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.hexString
        OperationQueue().addOperation {
            let registration = DeviceRegistration()
            registration.type = "apns"
            registration.token = token
            self.api.refreshDeviceRegistration(registration, callback: {
                (success) in
                debugPrint("Successfully refreshed registration with \(token)")
            })
        }
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        debugPrint("APNS error: \(error.localizedDescription)")
    }
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if userInfo["service"] as? Bool ?? false {
            if let user = User.fromJSON(userInfo["user"] as? [AnyHashable : Any]) {
                application.applicationIconBadgeNumber = user.unreadCount 
            }
        }
    }
    // Called when a notification is delivered to a foreground app.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .alert, .badge])
    }
    //Called to let your app know which action was selected by the user for a given notification.
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        parseNotificationPayload(userInfo: userInfo)
        OperationQueue.main.addOperation {
            // TODO: initialize correct tab
        }
    }
    
    var pushedThread : Int?
    var pushedReplyId : Int?
    var pushedUname : String?
    
    func parseNotificationPayload(userInfo:[AnyHashable: Any]) {
        self.pushedThread = userInfo["mid"] as? Int;
        self.pushedUname = userInfo["uname"] as? String;
        self.pushedReplyId = userInfo["rid"] as? Int;
    }
    
    func cleanupPushedData() {
        self.pushedUname = nil;
        self.pushedThread = nil;
        self.pushedReplyId = nil;
    }
    
    static var shared : AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    // MARK: UISceneSession Lifecycle
    
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
    
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    
}