Is it possible to show some kind of a local notification from an app, even if the app isn't running(also not in background)?
For example a daily reminder or something like that. I know that it is possible with push-notifications, but it doesn't fit for my app.
You can easily schedule local notifications, and they will be presented at the scheduled date and time regardless of the app's state.
First you need to get permission from the user to present notifications, like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound|UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
return true
}
Then you create the notification like this:
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "This is"
localNotification.alertBody = "A notification"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
Have a look at the Local and Remote Notification Programming Guide.
In AppDelegate, use this function instead
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
return true;
}
Most of the solutions outlined above have all been deprecated.
Use this UNUserNotification APIs instead
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
registerForLocalNotification()
return true
}
func registerForLocalNotification() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
print("Permission: \(granted)")
}
}
Related
I'm trying to set my notification system. Here how am I doing.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
application.registerForRemoteNotifications()
}
This is working great, except that the phone who receive the notification never play a sound. Like when I receive a Facebook notification or message notification.
I don't know why this is not working! Does someone got the same issue and/or know how to resolve it?
My application cannot call didRegisterForRemoteNotificationsWithDeviceToken on iOS10 devices, even the same code can call it on iOS11 devices.
I don't know why it happening and how to solve this issue.
If anyone knows answers, please help me.
my environment is below:
Xcode: 9.2
Swift: 3.2
deployment target: 10.0
my code is below:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) {granted, error in
if error != nil {
return
}
if granted {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = String(format: "%#", deviceToken as CVarArg) as String
let tokenWithoutSpace = token.replacingOccurrences(of: "[ |<>]", with: "", options: .regularExpression)
print(tokenWithoutSpace)
}
Thank you for your help.
Attempting to work with Firebase to register for remote notifications however when implementing the following code I get the error:
UNUserNotificationCenter is only available on iOS 10.0 or newer
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var soundID: SystemSoundID = 0
let soundFile: String = NSBundle.mainBundle().pathForResource("symphony", ofType: "wav")!
let soundURL: NSURL = NSURL(fileURLWithPath: soundFile)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
AudioServicesPlayAlertSound(soundID)
Fabric.with([Twitter.self])
//Firebase configuration
FIRApp.configure()
//Resource code from stackoverflow to create UNUserNotificationCenter
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
return true
}
By doing a simple "Fix-it" doesn't resolve my issue by creating an if statement based on the OS version number. What should I be doing or thinking towards this solution for the UserNotifications framework?
For one thing, with the new UNUserNotificationCenter, you only want to register for remote notifications if the user grants permission. The way your code is setup, you're trying to do it regardless of permission which could be one of the reasons. You should do something like this:
import UserNotifications
...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
return true
}
If you need to check if the user has an OS lower than iOS 10.0 - you could try something like this to include the old system:
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
} else {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
UIUserNotificationType.Badge, categories: nil))
}
Let me know if this works, and if it's what you're trying to accomplish. If not, I'll remove my answer.
I need create in my app a code that receive a remote information and push it to user when app is on background, I read on web that I need to use didReceiveRemoteNotification on appDelegate, to use remote push notication. I read something about and I need keys and certificates, I do not understand how to use didReceiveRemoteNotification
I need to learn about to push remote notification and how to use. I would like a tutorial or example how create it using swift 2.3.
I used this link and I found it the most helpful
http://www.appcoda.com/push-notification-ios/
I used this app for testing
https://itunes.apple.com/us/app/easy-apns-provider-push-notification/id989622350?mt=12
This is the code I have in my AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
registerForPushNotifications(application)
print(UIDevice.currentDevice().identifierForVendor!.UUIDString)
return true
}
func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Device Token:", tokenString)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register:", error)
}
I've configured my program to receive notification from Parse and I've enabled it with these lines :
var pushSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()
let userNotificationTypes = (UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound);
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
The declaration is in the
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
from my appDelegate, but when I close my program and relaunch it, all of the parameters are reset and I get them "off"
Does anyone have an idea?