The bottom line is that I made one local notification for a time interval of 10 seconds.
How do I add multiple notifications to this code with different time delays? That is, different notifications with different delays (several hours, days, and so on).
If this is possible, please use the example of my code.
I was told that I need to put a different identifier: "content" and different times. But I don't understand what parts of the code I need to duplicate.
import UIkit
import UserNotifications
class ViewController UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Hi"
content.body = "Bear"
content.sound = UNNotificationSound.default
content.threadIdentifier = "local-notifications"
let date = Date(timeIntervalSinceNow: 10)
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "content", content: content, trigger: trigger)
center.add(request) {(error) in
if error != nil {
print (error)
}
}
}
```
You can create method scheduleNotification(identifier:content:date:) in UNUserNotificationCenter extension ,
extension UNUserNotificationCenter {
func scheduleNotification(identifier: String, content: UNMutableNotificationContent, date: Date) {
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
self.add(request) {(error) in
if error != nil {
print (error)
}
}
}
}
Now, call this method for multiple notifications with the appropriate parameters that you want to use, i.e.
Example-1:
let content1 = UNMutableNotificationContent()
content1.title = "Hi"
UNUserNotificationCenter.current().scheduleNotification(identifier: "content1", content: content1, date: Date(timeIntervalSinceNow: 10))
Example-2:
let content2 = UNMutableNotificationContent()
content2.title = "Hello"
UNUserNotificationCenter.current().scheduleNotification(identifier: "content2", content: content2, date: Date(timeIntervalSinceNow: 20))
Related
I'm trying to schedule a local notification to fire every day, at a specific time, but from tomorrow.
e.g. "Trigger a notification every day at 2 pm, from tomorrow"
This is how I set up my schedule function.
func scheduleNotifications(date: Date, identfier: String, after: Bool) {
let content = UNMutableNotificationContent()
content.title = "App"
content.body = "Test."
content.sound = .default
content.userInfo = ["Hour": Int(hourFormatter.string(from: date)) ?? 0]
let afterDay = Calendar.current.date(byAdding: .day, value: after ? 1 : 0, to: Date())
var components = Calendar.current.dateComponents([.hour, .minute], from: afterDay!)
components.hour = Int(hourFormatter.string(from: date)) ?? 0
components.minute = Int(minuteFormatter.string(from: date)) ?? 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
This code is for daily notification just call it in tomorrow schedule time
func setupNotificationSettings() {
DispatchQueue.main.async {
let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.title = AppName
content.body = "APP_Body"
content.sound = UNNotificationSound.default
let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
let request: UNNotificationRequest = UNNotificationRequest(identifier: "\(AppName)_Local", content: content, trigger: trigger)
let center: UNUserNotificationCenter = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
center.add(request) { (error) in
}
}
}
How can I change up my code to allow my notification to trigger every 12 hours since the last API call. In the code, you can see where I commented out the variable containing the last API call (lastRefreshDate)
// let lastRefreshDate = userDefaults.object(forKey: Constants.Defaults.LATEST_REQUEST_TIME) as? Date
var dateComponents = DateComponents(calendar: Calendar.current, hour: 12, minute: 0)
if let date = UserDefaults.getDate() {
dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
}
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request) { (error) in
if error != nil {
print(error!)
}
}
I would like to schedule a local notification from iOS14 widget.
How can I do it?
I tried implementing the following:
let center = UNUserNotificationCenter.current()
center.delegate = self
let content = UNMutableNotificationContent()
content.title = "Some Title"
content.body = "Some Body"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString,
content: content, trigger: trigger)
center.add(request) { (error) in
if error != nil {
// Handle any errors.
}
I did with this.
func createDate(day: Int, month : Int, hour: Int, minute: Int, year: Int)->Date{
var components = DateComponents()
components.hour = hour
components.minute = minute
components.year = year
components.day = day
components.month = month
components.timeZone = .current
let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: components)!
}
// 📢///CreateNitification
func scheduleNotification(at date: Date, identifierUnic : String, body: String, titles:String) {
let triggerWeekly = Calendar.current.dateComponents([.day, .month, .hour,.minute, .year], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default
content.categoryIdentifier = "todoList2"
let request = UNNotificationRequest(identifier: identifierUnic, content: content, trigger: trigger)
// UNUserNotificationCenter.current().delegate = self
/// UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["textNotification2"])
/// UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print(" We had an error: \(error)")
}}
}
// Call
func callNotifications(){
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let adte = createDate(day: 3, month: 6, hour: 16, minute: 51, year: 2021)
scheduleNotification(at: adte, identifierUnic: UUID().uuidString, body: "Widgets on Work", titles: "check 123")
}
func getTimeline(in context: Context, completion: #escaping (Timeline<Entry>) -> ()) {
callNotifications()
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
Notification is working fine
but one thing is pending, how can I call UNUserNotificationCenter.current().delegate = self?
Thanks
I am trying to get a user to enter the time to take medicine or when they have an appointment in a text field and then send an alarm or notification at that time. I am a newbie so I don't know how to send notifications and such. I would need to do multiple of these depending on how many the user wants.
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
// Change the time to 7:00:00 in your locale
components.hour = 7
components.minute = 0
components.second = 0
let date = gregorian.date(from: components)!
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: CommonViewController.Identifier, content: content, trigger: trigger)
print("INSIDE NOTIFICATION")
UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
if let error = error {
print("SOMETHING WENT WRONG")
}
})
after minimizing/closing(if possible) the application, it is necessary to contact the server every n minutes and, if necessary, display push notifications. With push notifications, the code turned out to be the following
func sendNotification(inSeconds seconds: TimeInterval, completion: (Bool) -> ()){
removeNotification(withIdentifiers: ["inurewd"])
let date = Date(timeIntervalSinceNow: seconds)
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.month, .day, .hour, .minute, .second], from : date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "inurewd", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
}
func removeNotification(withIdentifiers identifiers: [String]){
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: identifiers)
but I can not understand the work of the application in the background. Can u help me, what method will suit me and how to implement it ?