I'm using Swift4:
I want to create firebase push notification, i'd follow steps as this video firebase push notification
and this is the app delegate code:
import UIKit
import IQKeyboardManagerSwift
import FBSDKLoginKit
import TwitterKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("user tooooken: ", Common.getUserToken())
FirebaseApp.configure()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if(error == nil) {
print("successful authentication")
}
}
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshToken(notification:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
UIApplication.shared.statusBarView?.backgroundColor = UIColor(red:255/255.0, green:51/255.0, blue:255/255.0, alpha: 1.0);
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
TWTRTwitter.sharedInstance().start(withConsumerKey:"xxxxxxxxxxx", consumerSecret:"xxxxxxxxxxxxxxxxxx")
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func applicationWillResignActive(_ application: UIApplication) {
FBSDKAppEvents.activateApp()
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = false
}
func applicationDidBecomeActive(_ application: UIApplication) {
FBHandler()
}
///// Twitter authentication //////
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if TWTRTwitter.sharedInstance().application(app, open: url, options: options) {
return true
}
return true
}
#objc func refreshToken(notification: NSNotification) {
let refreshToken = InstanceID.instanceID().token()!
print(refreshToken)
FBHandler()
}
func FBHandler() {
Messaging.messaging().shouldEstablishDirectChannel = true
}
}
when I push notification from firebase server it delivered successfully to the device, but when the php server sent push notification it doesn't work, is i forget any step ?
Make sure these:
you have sent firebase FCM token of your device to your server.
If your server sent you a data notification then it's data object
should be in 'notification' key.
Also when user logout from device you should have to delete user's FCM
token from server.
Related
Everything works fine after the second time. this issue only occurs once per device, making it hard to debug.
Even if I restarted the device issue doesn't appear again but as it always happens for new users the first time.
AppDelegate.Swift
import UIKit
import Flutter
import flutter_downloader
import Firebase
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
if(!UserDefaults.standard.bool(forKey: "Notification")) {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UserDefaults.standard.set(true, forKey: "Notification")
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
super.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
let firebaseAuth = Auth.auth()
Messaging.messaging().appDidReceiveMessage(userInfo)
print(userInfo)
if (firebaseAuth.canHandleNotification(userInfo)){
completionHandler(.noData)
return
}
}
}
private func registerPlugins(registry: FlutterPluginRegistry) {
if (!registry.hasPlugin("FlutterDownloaderPlugin")) {
FlutterDownloaderPlugin.register(with: registry.registrar(forPlugin: "FlutterDownloaderPlugin")!)
}
}
Crash Log:
specialized AppDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:) + 600 (AppDelegate.swift:29)
I've used apple push notification service in my app and I received certificates and it works well But now my problem is that when I use Firebase rest API for sending message as notification I won’t receive any notification in my iPhone until I run the app But when I use Firebase it will be working, well here is my codes:
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshToken(notification:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
Messaging.messaging().isAutoInitEnabled = true
FirebaseApp.configure()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert , .badge , .sound]) { (success, error) in
}
} else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
// Fallback on earlier versions
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
#if PROD_BUILD
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .prod)
#else
InstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox)
#endif
Messaging.messaging().subscribe(toTopic: "global")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
Messaging.messaging().subscribe(toTopic: "global")
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
if Messaging.messaging().fcmToken != nil {
Messaging.messaging().subscribe(toTopic: "global")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = false
}
func applicationDidBecomeActive(_ application: UIApplication) {
FBHandler()
}
#objc func refreshToken(notification : NSNotification) {
let refreshToken = InstanceID.instanceID().token()!
print("***\(refreshToken)")
FBHandler()
}
func FBHandler() {
Messaging.messaging().shouldEstablishDirectChannel = true
}
}
For APNS to work in background you need to enable background modes in capabilities section and tick remote notification.
Once you done add/check this delegate method in AppDelegate class
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("APNS USER INFO: \(userInfo)")
}
This method fires when app is in background and APNS comes.
More Info: How to handle push notification in background in ios 10?
UPDATE:
Add this one also and let see if it works
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
print("APNS: \(response.notification.request.content.userInfo)")
}
My push notifications sent from the Firebase console does not appear.. Yesterday, they appeared when i deleted my app, and freshly installed again - but only 1 time, and then they stopped appearing again. Today they dont appear at all..
I've tried to renew my APNs certificate, to create a new app on Firebase, to run the examplecode, check for correct bundle identifiers, check settings in xcode and now im lost for ideas..
I am able to receive push notifications from an APNs-tester, so I'm quite sure my certificate is good! It must be a Firebase problem somehow..
Here's my appDelegate:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .Default
// Parse
User.initialize()
PFCategory.initialize()
Follow.initialize()
Activity.initialize()
PostElement.initialize()
PFComment.initialize()
Socials.initialize()
Notification.initialize()
let configuration = ParseClientConfiguration {
$0.applicationId = "Agpq2y3O2Gxxxxxx"
$0.clientKey = "k2bM8XTYf354fxAxxxxxxxxxx"
$0.server = "https://parseapi.back4app.com/"
$0.localDatastoreEnabled = false
}
Parse.initializeWithConfiguration(configuration)
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
// Firebase configuration
FIRApp.configure()
// Facebook
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)
//Register for remote notifications
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
return true
}
// When app registered for remote notification
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("** DEVICE TOKEN = \(deviceToken) **")
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
print("** APNS Token set!! **")
}
// When app failed to register for remote notification
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
// Print the error, if failing to register for push notifications
print("AppDelegate, failed with registering for remote notifications: \(error)")
}
// If no token, or token has changed, this method is called to refresh it!
func tokenRefreshNotification(notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print("didRegisterUserNotificationSettings")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) {
// Let FCM know about the message for analytics etc.
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
// 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.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Let FCM know about the message for analytics etc.
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
// 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.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print(userInfo)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return PDKClient.sharedInstance().handleCallbackURL(url) || FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
print("------APP IN BACKGROUND!!!!!------")
// Setting the user to offline in Parse - be aware of bad connection, this may fuck it up
api.setOnlineStatus("offline")
// Setting the batchnumber to 0 and disconnecting from FCM
application.applicationIconBadgeNumber = 0;
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
print("------APP DID BECOME ACTIVE!!!!!------")
firebase = FirebaseManager()
connectToFcm()
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
}
}
I cant see whats missing - have anyone experienced the same problem, or know about a possible solution? :)
Best regards!
Hello I'm making an iPhone app where I send push notifications via Google's Firebase. I'm using Swift and Xcode for the programming. When I open the app I get asked to allow push notifications, however I don't receive any when I send them from the Firebase Console. I was wondering if you could help me out. I'm using Ad Hoc export to transfer an .isa to my friend's iPhone and test it that way. I followed exactly the Firebase tutorial - adding the .plist, the cocoa pod and I uploaded a certificate in the project settings. I have a paid apple developer account.
import UIKit
import CoreData
import Firebase
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert,UIUserNotificationType.Badge,UIUserNotificationType.Sound]
let notificationSettings = UIUserNotificationSettings(forTypes:notificationTypes, categories:nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("MessageID : \(userInfo["gcm_message_id"]!)")
print("%#", userInfo)
}
}
There are a few more things you need to do. When you registerForRemoteNotifications, you receive an APNS Token which you need to give to Firebase. This is done in application didRegisterForRemoteNotificationsWithDeviceToken.
import UIKit
import CoreData
import Firebase
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
super.init()
FIRApp.configure()
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(
UIUserNotificationSettings(
forTypes: [.Alert, .Badge, .Sound],
categories: nil
)
)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification,
object: nil
)
return true
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
}
func applicationDidBecomeActive(application: UIApplication) {
FIRMessaging.messaging().connectWithCompletion { (error) in
switch error {
case .Some:
print("Unable to connect with FCM. \(error)")
case .None:
print("Connected to FCM.")
}
}
}
func applicationWillResignActive(application: UIApplication) {}
func applicationWillEnterForeground(application: UIApplication) {}
func applicationWillTerminate(application: UIApplication) {}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("MessageID : \(userInfo["gcm.message_id"]!)")
print("%#", userInfo)
}
func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("Instance ID token: \(refreshedToken)")
}
applicationDidBecomeActive(UIApplication.sharedApplication())
}
}
I am a new developer, and I am currently making my first app.
Sometimes when I try to open the app, the icon dims, but nothing happens, and the whole phone briefly becomes unresponsive. My guess is this is happening in app delegate. I'm not sure what is happening, but I think I should be using grand central dispatch.
this is currently my code in app delegate,
import UIKit
import Firebase
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Facebook SharedInstance FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
//Firebase Database
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
//Onesignal PushNotifications
_ = OneSignal(launchOptions: launchOptions, appId: "3b2b4845-0b6a-4e92-892f-254c2cf51da8", handleNotification: nil)
_ = OneSignal(launchOptions: launchOptions, appId: "3b2b4845-0b6a-4e92-892f-254c2cf51da8", handleNotification: { (message, additionalData, isActive) in
NSLog("OneSignal Notification opened:\nMessage: %#", message)
if additionalData != nil {
NSLog("additionalData: %#", additionalData)
// Check for and read any custom values you added to the notification
// This done with the "Additonal Data" section the dashbaord.
// OR setting the 'data' field on our REST API.
if let customKey = additionalData["customKey"] as! String? {
NSLog("customKey: %#", customKey)
}
}
}, autoRegister: true)
print("didFinishLaunchingWithOptions launchOptions")
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
print("application")
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
Is it possible, that this has nothing to do with app delegate?
if it is in app delegate how can use GCD to make this work
remove
import FirebaseMessaging
and
FIRDatabase.database().persistenceEnabled = true
from the AppDeleget and try running it