ios - 基于日历的本地通知不起作用 - Swift 3

标签 ios swift date notifications unusernotificationcenter

我设置了一个本地通知系统,以便我可以在每天的特定时间发出通知。这个时间由用户确定,我将其存储为字符串。我将分解我在代码中完成的所有步骤,但基本上,我的问题是通知不会触发。

第 1 步: 在此步骤中,我设置了一个警报以请求发送通知的权限:

let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
center.requestAuthorization(options: options) { (granted, error) in
    if granted {
        application.registerForRemoteNotifications()
    }
}

第 2 步: 在此步骤中,我设置了调用来发送通知的函数:

static func sendNotification(stringDate: String) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"

        let content = UNMutableNotificationContent()
        content.title = "Title"
        content.body = "Detail"
        content.badge = 1

        if let date = dateFormatter.date(from: stringDate) {
            let calendar = Calendar.current

            let hour = calendar.component(.hour, from: date)
            let minute = calendar.component(.minute, from: date)

            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: "dateDone", content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
    }

第 3 步: 然后我在我的应用程序委托(delegate)文件中调用此函数,如下所示:

func applicationDidEnterBackground(_ application: UIApplication) {
    let defaults = UserDefaults.standard
    if defaults.object(forKey: "currentUser") != nil {
        if User.current.desiredTimeForNews.characters.contains("A") {
            let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "AM", with: "")
            HelperFunctions.sendNotification(stringDate: stringToBeConverted)

        } else {
            let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "PM", with: "")
            HelperFunctions.sendNotification(stringDate: stringToBeConverted)
        }
    }
}

重要:正如您在我的函数中看到的,我采用了“stringDate”参数。该变量有一个我的日期的字符串值。然后我将其转换为日期值。通过使用断点和打印语句,我发现我的所有值(包括日期、小时、分钟等)都不为零。

总的来说,我的问题是通知从未发送。但是我知道它被调用,因为我已经使用断点来证明这一点。任何帮助将不胜感激!

最佳答案

就我个人而言,我在真实设备上运行了它并且它有效。虽然它应该可以在模拟器上运行,但它不适合我。因此,在查看其他内容之前,我会尝试在真实设备上运行它!

关于ios - 基于日历的本地通知不起作用 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377592/

相关文章:

swift - Swift 中的字典值

javascript - 防止输入无效日期的 AngularJS 指令

java - 获取给定日期的哪一天以排除两个日期之间的差异

ios - Objective-C/C。当我尝试在 IOS 设备上获取 Mac 地址时,我得到了错误的值

ios - 使用另一个 View 中的按钮编辑 UITableView

android - 统一二维 : How to support multi platform and different aspect ratio devices in Unity 2D?

xcode - 快速将事件分派(dispatch)给父 ViewController

javascript - 解析 utc 时,从现在开始的时刻在 5 小时后返回

ios - 在 iOS 中使用 Geocoder 类根据地址获取经纬度

javascript - Titanium ios 选择器上的列未对齐