Метод didUpdate не вызывается в первый раз при реализации push-уведомлений VOIP с использованием pushkit
Я могу отправить VOIP push-уведомление, используя следующий код:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate {
var window: UIWindow?
var isUserHasLoggedInWithApp: Bool = true
var checkForIncomingCall: Bool = true
var userIsHolding: Bool = true
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 8.0, *){
let viewAccept = UIMutableUserNotificationAction()
viewAccept.identifier = "VIEW_ACCEPT"
viewAccept.title = "Accept"
viewAccept.activationMode = .foreground
viewAccept.isDestructive = false
viewAccept.isAuthenticationRequired = false
let viewDecline = UIMutableUserNotificationAction()
viewDecline.identifier = "VIEW_DECLINE"
viewDecline.title = "Decline"
viewDecline.activationMode = .background
viewDecline.isDestructive = true
viewDecline.isAuthenticationRequired = false
let INCOMINGCALL_CATEGORY = UIMutableUserNotificationCategory()
INCOMINGCALL_CATEGORY.identifier = "INCOMINGCALL_CATEGORY"
INCOMINGCALL_CATEGORY.setActions([viewAccept,viewDecline], for: .default)
if application.responds(to: #selector(getter: UIApplication.isRegisteredForRemoteNotifications))
{
let categories = NSSet(array: [INCOMINGCALL_CATEGORY])
let types:UIUserNotificationType = ([.alert, .sound, .badge])
let settings:UIUserNotificationSettings = UIUserNotificationSettings(types: types, categories: categories as? Set<UIUserNotificationCategory>)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
else{
let types: UIRemoteNotificationType = [.alert, .badge, .sound]
application.registerForRemoteNotifications(matching: types)
}
self.PushKitRegistration()
return true
}
//MARK: - PushKitRegistration
func PushKitRegistration()
{
let mainQueue = DispatchQueue.main
// Create a push registry object
if #available(iOS 8.0, *) {
print("here1")
let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)
// Set the registry's delegate to self
voipRegistry.delegate = self
// Set the push type to VoIP
voipRegistry.desiredPushTypes = [PKPushType.voIP]
} else {
// Fallback on earlier versions
}
}
@available(iOS 8.0, *)
func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) {
// Register VoIP push token (a property of PKPushCredentials) with server
print("during registration ")
//print(credentials.token)
// Swift 2 format
// let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes),
// count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")
// Swift 4 format
let token = credentials.token.map { String(format: "%02x", $0) }.joined()
print(token)
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
print("incomming push escaping")
}
func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenForType type: PKPushType) {
print("invalid")
}
@available(iOS 8.0, *)
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
print("incoming push")
// Process the received push
// Below process is specific to schedule local notification once pushkit payload received
var arrTemp = [AnyHashable: Any]()
arrTemp = payload.dictionaryPayload
let dict : Dictionary <String, AnyObject> = arrTemp["aps"] as! Dictionary<String, AnyObject>
if isUserHasLoggedInWithApp // Check this flag then only proceed
{
if UIApplication.shared.applicationState == UIApplicationState.background || UIApplication.shared.applicationState == UIApplicationState.inactive
{
if checkForIncomingCall // Check this flag to know incoming call or something else
{
var strTitle : String = dict["alertTitle"] as? String ?? ""
let strBody : String = dict["alertBody"] as? String ?? ""
strTitle = strTitle + "\n" + strBody
let notificationIncomingCall = UILocalNotification()
notificationIncomingCall.fireDate = Date(timeIntervalSinceNow: 1)
notificationIncomingCall.alertBody = strTitle
notificationIncomingCall.alertAction = "Open"
notificationIncomingCall.soundName = "SoundFile.mp3"
notificationIncomingCall.category = dict["category"] as? String ?? ""
//"As per payload you receive"
notificationIncomingCall.userInfo = ["key1": "Value1" ,"key2": "Value2" ]
UIApplication.shared.scheduleLocalNotification(notificationIncomingCall)
}
else
{
// something else
}
}
}
}
}
Но учетные данные didUpdate: PKPushCredentials не вызывается в первый раз. В консоли есть push-ключ для печати токена устройства. Но я не знаю, откуда он печатает токен устройства.
Итак, я не могу хранить этот токен устройства. Если я запускаю это приложение второй раз, не удаляя предыдущее, вызывается метод didUpdate. Как я могу получить токен устройства при первом запуске приложения, чтобы я мог сохранить этот токен в UserDefaults?