I want to create a userNotification that'll be shown in Notification Center while the app is running.
Clicking the notification will terminate the app.
Which trigger needs to be used?
How do I achieve this functionality?
Try this.
func scheduleNotification(at date: Date, body: String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Dont Forget"
content.body = body
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
Related
I'm trying to trigger local notifications for every 1 minute even in terminated state and background state. But, my app should not trigger notification when time is after 06:00PM. Below is my code.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,repeats: true)
//UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}
To handle local notification, try this:
public func addLocalNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize
let center = UNUserNotificationCenter.current()
// Set its content
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
// whenever you want to notify user select time
var dateComp = DateComponents()
dateComp.calendar = Calendar.current
dateComp.hour = hour
dateComp.minute = minute
// repeat and date
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
// Initializing the Notification Request object
let req = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Add the notification to the center
center.add(req) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}
hi I want to make a local notification from string time, I want the notification launch 10 minute before given time. I have trouble how to make the time from 4:01 into 3:51, please help. this is my code
let a = "4:01"
func startNoftification(prayer: String) {
let time = prayer.split(separator: ":").map { (x) -> Int in
return Int(String(x))!
}
let content = UNMutableNotificationContent()
content.title = "Adzan"
content.body = "it's time to sholat dzuhur"
let gregorian = Calendar(identifier: .gregorian)
var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
component.hour = time[0]
component.minute = time[1] - 10
guard let date = gregorian.date(from: component) else { return }
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let err = error {
print("Notif error:", err)
return
}
}
}
Is this what you need?
let time = "4:01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
guard let date = dateFormatter.date(from: time) else {
return
}
let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
let targetTimeString = dateFormatter.string(from: targetTime)
print(targetTimeString) // Prints 3:51
Or if your countdown time has a lot of time components, use DateComponents.
var dateComponents = DateComponents()
dateComponents.minute = -10
// Other components
if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
print(dateFormatter.string(from: targetTime))
}
Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.
First import UserNotification in appDelegate and in your controller
import UserNotification
and add code for didFinishWithLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
if let err = error {
print("Notifications permission denied because:", err)
return
}
if granted {
print("Notifications permission granted.")
}
}
}
and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad
let adzan = "4:01"
let content = UNMutableNotificationContent()
content.title = "Adzan"
content.body = "It's time for sholat"
content.sound = UNNotificationSound.default
// Format the date first from string time
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
//addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }
// and convert our date into dateComponents
let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
hello i want to send notification like daily reminder even the app terminated not working in background how i can do it and this my code
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func soundNotification(){
let prayers = ["fajer","dohor","asr","maghreb","isha"]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let content = UNMutableNotificationContent()
content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
content.body = " "
content.badge = 1
content.sound = UNNotificationSound(named: "salah.mp3")
let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}
Trigger local Notification at date and time.
func scheduleNotification(at date: Date, message:String) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = message
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
}
}
}
I am trying to send a local notification. My Code is Below mentioned.
Problem Is that notification not fire. i tried all possible answered on stackoverflow. please suggest.
I clear all Notification on did finish launching and also set a user permission for the notification
func applicationWillTerminate(_ application: UIApplication) {
self.loadData()
for obj in eventArray
{
if (obj["notification"] as? Bool)!
{
scheduleNotification(obj["time"] as! Date, obj["title"] as! String)
print(obj["time"] as! Date)
}
}
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func scheduleNotification(_ date: Date, _ title:String) {
let formatter = DateFormatter()
formatter.dateFormat = "HH"
let myhour = formatter.string(from: date)
let number = NumberFormatter()
let mynumberhour = number.number(from: myhour)
let intHour = mynumberhour?.intValue
print(intHour!)
formatter.dateFormat = "mm"
let myminute = formatter.string(from: date)
let mynumberMinute = number.number(from: myminute)
let intMinute = mynumberMinute?.intValue
print(intMinute!)
formatter.dateFormat = "MM"
let mymonth = formatter.string(from: date)
let mynumberMonth = number.number(from: mymonth)
let intMonth = mynumberMonth?.intValue
print(intMonth!)
formatter.dateFormat = "dd"
let myday = formatter.string(from: date)
let mynumberday = number.number(from: myday)
let intday = mynumberday?.intValue
print(intday!)
let calendar = Calendar.current
//let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: intMonth, day: intday, hour: intHour, minute: intMinute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
let content = UNMutableNotificationContent()
content.title = " Today's Event"
content.body = "Event Is Generated"
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: title, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
Problem I solved.
I called a "func scheduleNotification" in "func applicationDidEnterBackground" and notification fire properly.
I'm trying to schedule a local notification to fire every day (i.e. repeats), at a specific time, but from tomorrow.
i.e "Trigger a notifcation every day at 8pm, from tomorrow"
I've been using this SO question as guidance, and I believe I am doing what it says but I am still getting a notification today when I run the following code (if I schedule the notification before 8pm for instance):
func testDateNotification(){
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "This is a test"
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())
let userCalendar = Calendar.current
var components = userCalendar.dateComponents([.hour, .minute], from: tomorrow!)
components.hour = 20
components.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if ((error) != nil){
print("Error \(String(describing: error))")
}
}
}
import UserNotifications
Check for user permission
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
if $0 { } }
Add notification
let fromDate = Date(timeIntervalSince1970: Double(0.0))
let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
print(trigger.nextTriggerDate() ?? "nil")
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {
if let error = $0 {
print(error)
return
}else {
print("scheduled")
}
}