Как я могу отправить локальное push-уведомление iOS на определенную дату и запланировать его на будний день на определенIOS

Программируем под IOS
Ответить
Anonymous
 Как я могу отправить локальное push-уведомление iOS на определенную дату и запланировать его на будний день на определен

Сообщение Anonymous »

Я хочу добавить и отправить локальное push-уведомление iOS на определенную дату и запланировать его на день недели на определенное время (час, минута). Я хотел отправить это напоминание по будням, но хочу удалить сегодняшнее, если пользователь уже достиг своей сегодняшней цели. Я попробовал использовать приведенный ниже код, но не смог его отправить. Проверьте код ниже.
import UIKit
import UserNotifications

public extension Date {
func noon(using calendar: Calendar = .current) -> Date {
calendar.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
func day(using calendar: Calendar = .current) -> Int {
calendar.component(.day, from: self)
}
func weekday(using calendar: Calendar = .current) -> Int {
calendar.component(.weekday, from: self)
}
func hour(using calendar: Calendar = .current) -> Int {
calendar.component(.hour, from: self)
}
func minute(using calendar: Calendar = .current) -> Int {
calendar.component(.minute, from: self)
}
func second(using calendar: Calendar = .current) -> Int {
calendar.component(.second, from: self)
}
func adding(_ component: Calendar.Component, value: Int, using calendar: Calendar = .current) -> Date {
calendar.date(byAdding: component, value: value, to: self)!
}
func monthSymbol(using calendar: Calendar = .current) -> String {
calendar.monthSymbols[calendar.component(.month, from: self)-1]
}
func addDay(n: Int) -> Date {
let calendar = Calendar.current
return calendar.date(byAdding: .day, value: n, to: self)!
}
}

class ViewController: UIViewController, UNUserNotificationCenterDelegate {
private let categoryID = "Category"

override func viewDidLoad() {
super.viewDidLoad()

UNUserNotificationCenter.current().delegate = self
let actionShowSomething = UNNotificationAction(identifier: "ShowSomething", title: "Show Something", options: [])
let category = UNNotificationCategory(identifier: categoryID, actions: [actionShowSomething], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
}

@IBAction func addNotification(_ sender: Any) {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
// Request Notification Settings
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }
self.scheduleLocalNotification()
})
case .authorized:
self.scheduleLocalNotification()
case .denied:
print("Application Not Allowed to Display Notifications")
case .provisional:
break
case .ephemeral:
break
@unknown default:
break
}
}
}

private func requestAuthorization(completionHandler: @escaping (_ success: Bool) -> ()) {
// Request Authorization
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
completionHandler(success)
}
}

// MARK: - ScheduleLocalNotification
private func scheduleLocalNotification() {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Title"
notificationContent.subtitle = "Subtitle"
notificationContent.body = "Body"
notificationContent.categoryIdentifier = categoryID

var dateComponents = DateComponents()
let calendar = Calendar.current
dateComponents.calendar = calendar
let date = Date()
let second = calendar.component(.second, from: date)
dateComponents.weekday = 2 + 7 // Monday = 2
dateComponents.second = second + 30

let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)

UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/785 ... eekday-for
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»