For ios 10 i used this for registering the push notifications :
Registering for Push Notifications in Xcode 8/Swift 3.0?
Is there a way to ask for the requestAuthorization(options:[.badge, .alert, .sound]) outside the appdelegate and the func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
The reason i ask is because i don't want to present the pop up for push notifications after the user has used the app for a bit. Any ideas?
Like #dan said it isn't necessary to request the notifications permission in the AppDelegate. You can do it wherever you want to. This is what you probably be doing for that.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if error == nil {
if success {
print("Permission granted")
// In case you want to register for the remote notifications
let application = UIApplication.shared
application.registerForRemoteNotifications()
} else {
print("Permission denied")
}
} else {
print(error)
}
}
And Remember
to import the UserNotifications framework where you use this code.
if you register for remote notifications you need to implement the didRegisterForRemoteNotificationsWithDeviceToken method in your AppDelegate
The question for me is the pop up won't show again once user agreed or denied it.
So we have to redirect users to Settings after that manually.
Here comes the code in Swift:
#IBAction func userDidClickButton(_ sender: Any) {
// initialise a pop up for using later
let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
// do something
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
// check the permission status
UNUserNotificationCenter.current().getNotificationSettings () { settings in
switch settings.authorizationStatus {
case .denied, .notDetermined:
self.present(alertController, animated: true, completion: nil)
case .authorized:
// continue the stuff
DispatchQueue.main.sync {
// Update UI
}
}
}
}
Related
last two days in Device token and VoIP token did not generate for the development environment
I have no change in code, 2 days ago its worked fine.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
let aps = notification["aps"] as! [String: AnyObject]
UIApplication.shared.applicationIconBadgeNumber = 0
}
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] (granted, error) in
print("Permission granted: \(granted)")
guard granted else {
print("Please enable \"Notifications\" from App Settings.")
self?.showPermissionAlert()
return
}
self?.getNotificationSettings()
}
} else {
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
#available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
//UserDefaults.standard.set(token, forKey: DEVICE_TOKEN)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("didReceiveRemoteNotification /(userInfo)")
guard let dict = userInfo["aps"] as? [String: Any], let msg = dict ["alert"] as? String else {
print("Notification Parsing Error")
return
}
}
func showPermissionAlert() {
let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
self?.gotoAppSettings()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(settingsAction)
alert.addAction(cancelAction)
DispatchQueue.main.async {
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
private func gotoAppSettings() {
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.openURL(settingsUrl)
}
}
I want to make a phone verification with Firebase, but I get a failure to send a notification. I'm sharing AppDelegate code. I couldn't figure out what I had to do? I performed certificate insertion. FirebaseAppDelegateProxyEnabled is value no
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
print("Permission granted: \(granted)") // 3
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
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 })
// For iOS 10 data message (sent via FCM
Messaging.messaging().delegate = self
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
}
Code send function
func sendCode(_ sender: Any) {
let alert = UIAlertController(title: "Phone number", message: "Is this your phone number? \n \(emailField.text!)", preferredStyle: .alert)
let action = UIAlertAction(title: "Yes", style: .default) { (UIAlertAction) in
PhoneAuthProvider.provider().verifyPhoneNumber(self.emailField.text!, uiDelegate: nil) { (verificationID, error) in
if error != nil {
print("eror: \(String(describing: error?.localizedDescription))")
} else {
let defaults = UserDefaults.standard
defaults.set(verificationID, forKey: "authVID")
}
}
}
let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
In my scenario, User will get an alert for receiving Notification in application. If the user clicks on "Don't Allow" UILabel is updated with "Not enabled". If the user wants to change the notification,User will be navigated to application setting page to change the notification permission status.
func checkNotificationPermission(){
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){
(granted, error) in
if granted == true {
DispatchQueue.main.async {
print("notificaation access true")
self.notificationAccessLbl?.text = "Enabled"
}
}
else {
DispatchQueue.main.async {
self.notificationAccessLbl?.text = "Not enabled"
}
}
}
UIApplication.shared.registerForRemoteNotifications() }
But when the user comes back to application, The UILabel is not getting updated when the user comes to application from Setting page.
for Updating the UILabel in application after the user comes from setting page to application. I Have Called
func checkNotificationPermission()
to update UILabel Value in ViewDidAppear() Method and I register the a function in applicationwillbecomeactive method() Kindly help me in this.
I have switch in setting page in application which allows user to enable disable push and that will be send on server but before that user must have allowed push from settings page of Device. here is my solution
I have created global object
var isPushEnabledFromSettings = false {
didSet {
// you can set label value here in main queue
}
}
and one method to check it
func isPushPermissionGiven (permission:#escaping (Bool) -> ()) {
if #available(iOS 10.0, *) {
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: {settings in
switch settings.authorizationStatus {
case .notDetermined:
permission(false)
case .denied:
permission(false)
case .authorized:
permission(true)
}
})
} else {
// Fallback on earlier versions
if UIApplication.shared.isRegisteredForRemoteNotifications {
permission(true)
} else {
permission(false)
}
}
}
and in view did load added these lines
self.isPushPermissionGiven { (permission) in
self.isPushEnabledFromSettings = permission
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) {[weak self] (notificaiont) in
guard let strongSelf = self else {return }
strongSelf.isPushPermissionGiven { (permission) in
DispatchQueue.main.async {
strongSelf.isPushEnabledFromSettings = permission
}
}
}
Now I have switch in setting page which allows user to enable disable push
#objc func switchChanged (sender:UISwitch) {
guard self.isPushEnabledFromSettings else {
AppDelegate.sharedDelegate.navigateUesrToSettings(withMessage: "Please grant push permission from settings")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
sender.setOn(false, animated: false)
})
return
}
}
func navigateUesrToSettings (withTitle title:String = "YourApp", withMessage message:String) {
let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let _ = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
self.navigate(To: UIApplicationOpenSettingsURLString)
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
AppDelegate.sharedDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
Hope it is helpful to you :)
I'm aware that there are some questions out there that are similar to this question, however, a lot of them are in Objective C and I haven't been able to find a really applicable solution yet that works.
The main problem I am having is that when I log out of one account in my app, then log into another, the tab bar is not reset, and it displays the previously signed in users data. In other words, I need a way to "reset" the app back to the state it was in before any user had signed in.
I have tried to achieve this by writing a function inside App Delegate (setupTabBarController) and calling it when the user logs out, but no such luck yet.
This is what I have so far:
Logout code:
#objc func handleSignOutButtonTapped() {
let signOutAction = UIAlertAction(title: "Sign Out", style: .destructive) { (action) in
do {
try Auth.auth().signOut()
let welcomeControl = WelcomeController()
let welcomeNavCon = UINavigationController(rootViewController: welcomeControl)
self.present(welcomeNavCon, animated: true, completion: nil)
} catch let err {
print("Failed to sign out with error", err)
Service.showAlert(on: self, style: .alert, title: "Sign Out Error", message: err.localizedDescription)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Service.showAlert(on: self, style: .actionSheet, title: nil, message: nil, actions: [signOutAction, cancelAction]) {
}
let delegate = AppDelegate()
delegate.setupTabBarController()
}
Part of my App Delegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
setupTabBarController()
return true
}
func setupTabBarController() {
window = UIWindow()
window?.makeKeyAndVisible()
let vc = MainTabBarController()
let controller = UINavigationController(rootViewController: vc)
window?.rootViewController = controller
}
Sign in code:
#objc func handleNormalLogin() {
hud.textLabel.text = "Signing In..."
hud.show(in: view, animated: true)
//TODO
guard let email = emailTextField.text else { return }
guard let password = passwordTextField.text else { return }
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if let error = error {
print("Error signing in: \(error)")
return
}
//sucessfully signed in
self.hud.dismiss(animated: true)
self.dismiss(animated: true, completion: nil)
}
}
Any help is really appreciated, I have been stuck on this for a few hours now and I really want to understand what I'm doing wrong.
Cheers
Problem
When you write let delegate = AppDelegate(). It means that you create a new AppDelegate. Instead of using current AppDelegate, you use another AppDelegate. That's why setupTabBarController method doesn't affects anything.
Calling setupTabBarController at the end of handleSignOutButtonTapped isn't a good idea. Because it will replace current rootViewController with UINavigation of MainTabBarController.
Answer
Use self.tabBarController? instead of self to present welcomeNavCon.
Don't call setupTabBarController at the end of handleSignOutButtonTapped method.
Recreate and set new viewControllers for MainTabBarController.
Code
#objc func handleSignOutButtonTapped() {
let signOutAction = UIAlertAction(title: "Sign Out", style: .destructive) { (action) in
do {
try Auth.auth().signOut()
let welcomeControl = WelcomeController()
let welcomeNavCon = UINavigationController(rootViewController: welcomeControl)
self.tabBarController?.present(welcomeNavCon, animated: true) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate;
appDelegate.resetTabBarController();
};
} catch let err {
print("Failed to sign out with error", err)
Service.showAlert(on: self, style: .alert, title: "Sign Out Error", message: err.localizedDescription)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Service.showAlert(on: self, style: .actionSheet, title: nil, message: nil, actions: [signOutAction, cancelAction]) {
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var tabBarController : UITabBarController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
setupTabBarController()
return true
}
func setupTabBarController() {
window = UIWindow()
window?.makeKeyAndVisible()
let vc = MainTabBarController()
let controller = UINavigationController(rootViewController: vc)
window?.rootViewController = controller
}
func resetTabBarController() -> Void {
let viewControllerAtIndex1 = ...
let viewControllerAtIndex2 = ...
let viewControllerAtIndex3 = ...
tabBarController?.viewControllers = [viewControllerAtIndex1, viewControllerAtIndex2, viewControllerAtIndex3];
}
}
I have sample app with a button. On click button should be taking the user to push notification service for my app to be able to disable them or enable.
I know how to get to the general setting with this sample code but I think for notification probably you need some additional parameters like bundleId.
My question is more about URL for push notification for my app not only get to general setup as this is shown on code sample below
Sample code:
#IBAction func pushNotificationSettings(button: UIButton) {
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
} else {
// Fallback on earlier versions
}
}
}
For IOS 10 or above
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
// Notifications are allowed
}
else {
// Either denied or notDetermined
let alertController = UIAlertController(title: nil, message: "Do you want to change notifications settings?", preferredStyle: .alert)
let action1 = UIAlertAction(title: "Settings", style: .default) { (action:UIAlertAction) in
if let appSettings = NSURL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(appSettings as URL, options: [:], completionHandler: nil)
}
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
}
alertController.addAction(action1)
alertController.addAction(action2)
self.present(alertController, animated: true, completion: nil)
}
}