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

时间:2019-06-17 14:27:39

标签: swift notifications uilocalnotification localnotification

我正在开发一个应用程序,用户可以创建带有标题,描述,日期和图片的“内存”。单击“保存”后,我希望该应用程序能够在用户选择其活动开始的日期时通知用户。 我尝试了此代码,但无法正常工作。 如果您可以修复我的代码或帮助我发现问题,我会很高兴:)

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 个答案:

答案 0 :(得分:1)

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)

notification的{​​{1}}之后的10 seconds处射击。

编辑2:

current Date()操作类似

saveMemory

编辑3:

这是我使用@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) } } } 获得future date的方式

UIDatePicker

在上面的代码中,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 property就是此时在returns中设置的date

相关问题