I am writing VoIP application using Xcode 9.2, Swift 4.0, minimum iOS version is 10.3. I want to receive incoming call even iPhone is in sleeping mode (just like WhatsApp or Viber). I already know that I must use CallKit for it. But I do not know how to receive PUSH Notifications correctly. I mean, I have two ways how to receive them. First is in AppDelegate.swift, please, look (this method is working):
import UIKit
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Getting permissions for Notifications
//222
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
}
application.registerForRemoteNotifications()
//222
return true
}
//For PUSH Notifications settings
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("NOTIFICATION ERROR: \(error)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let pushToken = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}).lowercased()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Receiving call?
}
}
But, no matter, what I am doing, it does not trigger incoming call if iPhone is sleeping. Lately I saw that there is another method to receive PUSH Notifications. Please, look:
import UIKit
import CallKit
import PushKit
class ViewController: UIViewController, CXProviderDelegate, PKPushRegistryDelegate {
override func viewDidLoad() {
let registry = PKPushRegistry(queue: nil)
registry.delegate = self
registry.desiredPushTypes = [PKPushType.voIP]
}
func providerDidReset(_ provider: CXProvider) {
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
action.fulfill()
}
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
print(pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined())
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: #escaping () -> Void) {
// Receive call?
}
}
The problem is that in first method I have this PUSH token: 9bcf73ac3d6a68be07c26d8b6a972f5b716cd5308f1a19048b62d19b9b8d4bd1
Second method returns me this PUSH token:
1e40fafb2963161b1bcf1bdde00d625a879c6934e19e2fb32f62b1c9272e956f
And they are not equal! How can this be? So, main question is: how to receive PUSH Notifications and what is difference between AppDelegate and PushKit methods and which token is correct?
Thank you for any help!
There are two types of Notifications (in fact more, but, in this case, just two): PUSH Notifications and VoIP Notifications. They have different tokens and different system of receiving. VoIP services exists only for calls (Apple CallKit), opposite PUSH service exists for messages and other notifications. So, in fact, both of this methods are necessary and one does not replaces another. And both of this methods requiring different Certificates in Apple Developer Account: Apple Push Notification service SSL for PUSH Notifications and VoIP Services Certificate for VoIP.
Thank you everyone for help! Be free to edit this if you see a error.
First of all remove this line application.registerForRemoteNotifications()
Now comes to puskit below method will have right token
func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) {
print("\(#function) voip token: \(credentials.token)")
let deviceToken = credentials.token.reduce("", {$0 + String(format: "%02X", $1) })
print("\(#function) token is: \(deviceToken)")}
and Push-kit framework does not have UI like remote or local notification you need to trigger local notification every time when below method called
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: #escaping () -> Void) {
// Receive call?
}
Related
I am building a screen with phone number login. I checked over and over again and the project is newly created, however, I am getting this log:
7.2.0 - [Firebase/Auth][I-AUT000015] The UIApplicationDelegate must handle remote notification for phone number authentication to work.
If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method.
I did read in the documentation about swizzling and I don't know why it seems to be disabled, I did not disabled it. I have added GoogleServices-Info.plist into the app, I added in firebase panel the app apn auth key.
My entry point in the app looks like this:
#main
struct partidulverdeApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
My URL Types property has an entry with the RESERVED_CLIENT_ID
I am very desperate about this problem. Any idea is highly appreciated.
Edit1:
I did read the documentation and tried to handle notification with swizzling disabled, but I get the same error:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Your code here")
return true
}
}
#main
struct partidulverdeApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
Here's how to implement Phone Number Auth using the new SwiftUI 2 life cycle:
Create a Firebase project and set up PhoneNumber Auth
Add your iOS app to the Firebase project, download and add GoogleService-Info.plist to your project
In Xcode, select the application target and enable the following capabilities:
Push notifications
Background modes > Remote notifications
Create and register an APNS authentication key on the Apple developer portal
Upload the key to Firebase (under Project Settings > Cloud messaging in the Firebase Console)
Add the Firebase project's reversed client ID to your app's URL schemes
In your Info.plist, set FirebaseAppDelegateProxyEnabled to NO
Implement the AppDelegate as follows:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
print("SwiftUI_2_Lifecycle_PhoneNumber_AuthApp application is starting up. ApplicationDelegate didFinishLaunchingWithOptions.")
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(#function)")
Auth.auth().setAPNSToken(deviceToken, type: .sandbox)
}
func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("\(#function)")
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
print("\(#function)")
if Auth.auth().canHandle(url) {
return true
}
return false
}
}
#main
struct SwiftUI_2_Lifecycle_PhoneNumber_AuthApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
print("Received URL: \(url)")
Auth.auth().canHandle(url) // <- just for information purposes
}
}
}
}
For further reading, I suggest these two articles I wrote:
Firebase and the new SwiftUI 2 Application Life Cycle
The Ultimate Guide to the SwiftUI 2 Application Life Cycle
I send notification I receive it on the phone no problem;
Now I want to customise image titre ...
the problem is this function on delegate was never called didReceiveRemoteNotification
On appDelegate didFinishLaunchingWithOptions:
// Dimelo: Push Notif and Badge
dimelo?.updateAppBadgeNumber = true
dimelo?.developmentAPNS = true
dimelo?.initialize(withApiSecret: BuildConfig.GetInstance().getDimeloApiSecret(), domainName: BuildConfig.GetInstance().getDimeloDomainName(), delegate: self)
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Register the device token.
Dimelo.sharedInstance().deviceToken = deviceToken
}
func dimeloDidBeginNetworkActivity(_ dimelo: Dimelo?) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func dimeloDidEndNetworkActivity(_ dimelo: Dimelo?) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
dimelo?.consumeReceivedRemoteNotification(userInfo)
}
I already activate remote notification on baclground mode
but the function didReceiveRemoteNotification was never called :(
I'm integrating this RingCentral Engage Digital / Dimelo library:
https://github.com/ringcentral/engage-digital-messaging-ios/issues
I have implemented this demo app using the Dimelo iOS SDK: https://github.com/tylerlong/GrandTravel-iOS/blob/master/GrandTravel/AppDelegate.swift
Could you please check my code and figure out the differences?
I suggest you to print logs for both handleActionWithIdentifier and didReceiveRemoteNotification.
If it still doesn't work, please send email to devsupport#ringcentral.com and we will investigate.
I develop an iOS app that use firebase phone authentication, I follow google documentation, but I always have the following error:
If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method.
and My appDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
}
func application(_ application: UIApplication , didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
if Auth.auth().canHandleNotification(notification)
{
completionHandler(UIBackgroundFetchResult.noData);
return
}
}
So how can I resolve that?
If swizzling is disabled, you need to do two things for phone number auth to work:
Set APNSToken on the FIRAuth instance with your APNs token. This is independent of setting APNs token for FCM (using the FCM client SDK is not required for using phone number auth).
Call canHandleNotification on the FIRAuth instance with the remote notification you received from the application:didReceiveRemoteNotification:fetchCompletionHandler: method on your UIApplicationDelegate instance. This is also independent of notifying FCM. It's documented in under section "Receive notifications without swizzling".
In a Swift 3 app, implementing Firebase 4 for notifications and a WKWebView for displaying an Angular web app I've come to a point where I can receive app notifications from Firebase and get an alert in the Notification Centre.
But when attempting to get app notifications from my server I only end up having them displayed in the console when running the app, but the phone does not display notifications at all.
I'm suspecting an issue with the way the messages from my server are formatted, below is the console output from a successful alert from Firebase:
[AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1504280715, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("aps"): {
alert = "This one works";
}, AnyHashable("google.c.a.c_id"): 7239776096663233136,
AnyHashable("gcm.message_id"): 0:1504280715823529%dc6002bbdc6002bb]
And here is a sample from my own app server, which does not display as a phone notification:
[AnyHashable("from"): 1001513747966, AnyHashable("body"): Urgent action
is needed to prevent your account from being disabled!,
AnyHashable("title"): Urgent action needed!]
Message ID: 0:1504280715823529%dc6002bbdc6002bb
I'm testing this on ios10 devices, only.
My AppDelegate.swift file looks like this:
import UIKit
import CoreData
import Fabric
import Crashlytics
import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseInstanceID
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self as MessagingDelegate
// [END set_messaging_delegate]
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
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)
}
Messaging.messaging().shouldEstablishDirectChannel = true
application.registerForRemoteNotifications()
// [END register_for_notifications]
Fabric.with([Crashlytics.self])
return true
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
Messaging.messaging()
.setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
Messaging.messaging().shouldEstablishDirectChannel = true
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//connectToFirebaseMessaging()
UIApplication.shared.applicationIconBadgeNumber = 0
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ViDent")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
// [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
// With swizzling disabled you must let Messaging know about the message, for Analytics
Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
And it is the print("Received data message: (remoteMessage.appData) at the very end of the AppDelegate.swift file which triggers and prints the message to the console, so I just need to work out how to pass these messages on so an alert is triggered on the device.
I am trying to sync data between a few Apple TVs using CloudKit and CKSubcription. The problem is application:didReceiveRemoteNotification: is never called when I add, delete, or update records. I believe I am configuring the subscriptions correctly and I have confirmed they are added to the CloudKit dashboard. I have repeatedly tried resetting the development environment in the dashboard, but that is not helping. I really don't want to create a timer to fetch every so often. Thanks for any help!
Also, I am using the private database in CloudKit and not the public database if that matters.
Here's my code:
AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
CloudKitManager.subscribeToItemUpdates()
application.registerForRemoteNotifications()
...
return true
}
CloudKitManager.swift
class func subscribeToItemUpdates() {
if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
saveSubscriptionWithIdentifier(uuid + "create", options: CKSubscriptionOptions.FiresOnRecordCreation)
saveSubscriptionWithIdentifier(uuid + "update", options: CKSubscriptionOptions.FiresOnRecordUpdate)
saveSubscriptionWithIdentifier(uuid + "delete", options: CKSubscriptionOptions.FiresOnRecordDeletion)
}
}
class func saveSubscriptionWithIdentifier(identifier: String, options: CKSubscriptionOptions) {
let sub = CKSubscription(recordType: "Message", predicate: NSPredicate(value: true), subscriptionID: identifier, options: options)
sub.notificationInfo = CKNotificationInfo()
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
publicDatabase.saveSubscription(sub) { (savedSubscription, error) -> Void in
if error != nil {
print("Error saving CloudKit subscription \(error)")
}
else {
print("Saved subscription to CloudKit", savedSubscription)
}
}
}
There is a slight difference between tvOS and iOS. In my demo app i handle it like this:
#if os(tvOS)
//This will only be called when your app is active. So this is what you should use on tvOS
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
EVLog("Push received")
EVCloudData.publicDB.didReceiveRemoteNotification(userInfo, executeIfNonQuery: {
EVLog("Not a CloudKit Query notification.")
}, completed: {
EVLog("All notifications are processed")
})
}
#else
// Process al notifications even if we are in the background. tvOS will not have this event
// Make sure you enable background notifications in the app settings. (entitlements: pushnotifications and backgrounds modes - notifications plus background fetch)
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
EVLog("Push received")
EVCloudData.publicDB.didReceiveRemoteNotification(userInfo, executeIfNonQuery: {
EVLog("Not a CloudKit Query notification.")
}, completed: {
EVLog("All notifications are processed")
completionHandler(.NewData)
})
}
#endif
For more information see EVCloudKitDao