Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all articles
Browse latest Browse all 16750

Schedule local notifications on user selected week days in iOS

$
0
0

The use case is that there is a form where a user can say: I want to get a notification on X days (e.g Monday, Friday and Sunday) at 14:00. The application is in react native but I'm just calling a native swift function to schedule the notification:

import Foundation
import UserNotifications

@objc(Reminders)
class Reminders: NSObject {
  @objc func setReminder(
    _ message: NSString,
    daysV days: NSArray,
    hourV hour: NSInteger,
    minuteV minute: NSInteger
  ) {
    // We'll replace all scheduled notifications entirely
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

    // Create a notification for each day that has been passed
    let daysC: [Int] = days.map { $0 as! Int }
    for day in daysC {
      var date = DateComponents()
      date.weekday = day
      date.hour = hour
      date.minute = minute

      let content = UNMutableNotificationContent()
      content.title = "Reminder"
      content.body = message as String

      let userCalendar = Calendar(identifier: .iso8601)
      let dateTime = userCalendar.date(from: date)
      let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: dateTime as! Date)
      let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
      let identifier = "TMWTE\(day)"
      let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
      let center = UNUserNotificationCenter.current()
      center.add(request, withCompletionHandler: { (error) in
        if let error = error {
          print(error);
        }
      })
    }
  }
}

What I'm trying to do is get each of the weekday included in a list sent from JS and schedule a notification for it. So if the user selects Monday and Wednesday the array will be [1,3] and I'll schedule a notification for each day respectively.

What's actually happening however is that I get X notifications at once in the first day. Thus if the user selects all days then in the next triggerDate I'll get 7 notifications.

Being a complete novice in Swift I may be doing something irrational, but I cannot figure it out at the moment. Now I've also tried to set the date.day to be the next Saturday, Sunday etc.. but that causes no notifications to be shown, which makes me think that I'm missing something basic here.

Thanks!


Viewing all articles
Browse latest Browse all 16750

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>