Swift - 未显示特定日期的通知

Swift - Notifications on a certain date not shown

我正在制作一个用户可以创建的应用程序 "memories",其中包含标题、说明、日期和图片。单击 'save' 后,我希望该应用能够在用户选择的活动开始日期通知用户。 我试过这段代码,但它不起作用。 如果您能修复我的代码或帮助我找到问题,我将不胜感激:)

future = sender.date(UIDatePicker 内的发送者)

(当然我写了import UserNotifications

@IBAction func saveMemorey(_ sender: UIButton) {        

    // User Notification code
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()

    content.title = "New MEmorey!"
    content.subtitle = "A New Event Starts Today:"
    content.body = txtTitle.text!

    content.sound = UNNotificationSound.default
    content.threadIdentifier = "local-notifications temp"

        let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: future)

        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)
        }
    }

    self.navigationController?.popViewController(animated: true) // Returns to the memories page after clicking 'save'
}

AppDeligate:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()

    let center = UNUserNotificationCenter.current()
    let options : UNAuthorizationOptions = [.sound, .alert]

    center.requestAuthorization(options: options) { (granted, error) in
        if error != nil {
            print (error)
        }
    }

    center.delegate = self
    return true
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}

future 相关:

 class AddMemoryViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var future = Date()
var dateToSet : Double = 0.0

// connections from storyboard to the code

@IBOutlet weak var countLabel: UILabel!

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
     future = sender.date

    //Use midnight today as the starting date
    guard let today = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) else { return }

    //Calculate the number of days between today and the =user's chosen day.
    let difference = Calendar.current.dateComponents([.day], from: today, to: future)
    guard let days = difference.day else { return }
    let ess = days > 1 ? "s" : ""
    if (days > 0)
    {
        countLabel.text = "That date is \(days) day\(ess) away."
    }
    if (days < 0)
    {
        countLabel.text = " \(abs(days)) day\(ess) since the event."
    }
    if (days == 0)
    {
        countLabel.text = " The event is today!"
    }
    dateToSet = Double(self.future.millisecondsSince1970)

}

AppDelegate,你需要先request authorization从用户发送通知到application(_:didFinishLaunchingWithOptions:) method的设备,即

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (allowed, error) in
        if allowed {
            print("User has allowed notifications")
        } else {
            print("User has declined notifications")
        }
    }
    return true
}

在上面的代码中,您可以根据需要提供options。请参阅此 link 以了解更多可能的 options

然后,一旦用户 authorization 成功,您就可以使用您的代码安排 notifications

编辑-1:

只是为了调试,通过将 future 值设置为来执行代码:

let future = Date(timeIntervalSinceNow: 10)

这与current Date() 10 seconds 之后的notification 一起火。

编辑-2:

saveMemory 动作是这样的,

@IBAction func saveMemorey(_ sender: UIButton) {
    let content = UNMutableNotificationContent()
    content.title = "New Memory!"
    content.subtitle = "A New Event Starts Today:"
    content.body = ""
    content.sound = .default

    let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: future)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

    let request = UNNotificationRequest(identifier: "content", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { (error) in
        if error != nil {
            print (error)
        }
    }
}

编辑 3:

下面是我如何使用 UIDatePicker

获得 future date
class VC: UIViewController {
    @IBOutlet weak var datePicker: UIDatePicker!

    var future: Date {
        return self.datePicker.date
    }

    @IBAction func saveMemorey(_ sender: UIButton) {
        //your code here....
    }

    //rest of the code...
}

在上面的代码中,futurecomputed propertyreturns 在那个时间点 datePicker 中设置的任何 date