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

Posted

技术标签:

【中文标题】Swift - 未显示特定日期的通知【英文标题】:Swift - Notifications on a certain date not shown 【发布时间】:2019-06-17 14:27:39 【问题描述】:

我正在制作一个应用程序,用户可以创建具有标题、描述、日期和图片的“记忆”。单击“保存”后,我希望应用程序能够在用户选择他的活动开始的日期通知用户。 我试过这段代码,但它不工作。 如果你能修复我的代码或帮助我找到问题,我会很高兴:)

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)


【问题讨论】:

【参考方案1】:

AppDelegate中,您需要先从用户request authorizationapplication(_: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

Edit-1:

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

let future = Date(timeIntervalSinceNow: 10)

这与来自current Date()10 seconds 之后的notification 一起触发。

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

Edit-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...

在上面的代码中,future 是一个computed propertyreturns 无论date 在那个时间点被设置在datePicker 中。

【讨论】:

刚刚添加了我的 AppDelegate 函数。对吗? 我的意思是我添加到 Q 中的 AppDelegate 函数以前就在那里 :)。其他东西可能效果不佳 试试我已添加答案的 Edit-1Edit-2 当我使用let future = Date(timeIntervalSinceNow: 10) 对其进行测试时,它运行良好...但这不是我编写代码的目的...用户是选择日期和应用程序假设发送的人该日期的通知... 我知道这不是您的代码的目的。这就是为什么我明确指定仅用于调试目的。无论如何,如果它工作正常,那么您选择日期的代码肯定有问题。将该特定代码添加到问题中,

以上是关于Swift - 未显示特定日期的通知的主要内容,如果未能解决你的问题,请参考以下文章

当特定屏幕以 html 显示时,从 WKWebView 向 Swift 获取通知

终止应用程序后未触发 AlarmManager 通知

设置特定日期和时间的本地通知 swift 3

UILocal 通知未显示

无法在 Swift 中将日期转换为特定格式

用户在swift中点击firebase通知后如何显示警报?