gpt4 book ai didi

ios - UILocalNotification 即使日期已过,也会继续触发

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:19 26 4
gpt4 key购买 nike

您好,我希望有人能帮我解决这个问题。我还是 ios 开发的新手。我正在测试 UILocalNotification,我能够设置 firedate 并且一切正常,但如果 firedate 在过去,本地通知会立即触发。此外,每次我退出应用程序时,通知都会再次出现在通知中心。无论如何要确保只有在日期设置为 future 时才会触发本地通知?我搜索了 SO 但我找不到我的答案。任何帮助将不胜感激。

这是viewDidLoad方法中的代码

class ViewController: UIViewController {


var time : NSDate?

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.


var comp = NSDateComponents()
comp.year = 2015
comp.month = 01
comp.day = 20
comp.hour = 16
comp.minute = 00
var calender = NSCalendar.currentCalendar()

time = calender.dateFromComponents(comp)

var notification = UILocalNotification()
notification.alertBody = "this works"
notification.fireDate = time
notification.timeZone = NSTimeZone.defaultTimeZone()



UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

这是AppDelegate中的代码

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
let notificationSetiings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSetiings)
return true
}

最佳答案

如果您将 fireDate 设置为过去的日期,通知将立即触发。Apple 在其 UILocalNotification documentation 中进行了很好的设计和记录。 .

fireDate Property

The date and time when the system should deliver the notification. Declaration

Swift

@NSCopying var fireDate: NSDate?

Objective-C

@property(nonatomic, copy) NSDate *fireDate

Discussion

The fire date is interpreted according to the value specified in the timeZone property. If the specified value is nil or is a date in the past, the notification is delivered immediately.

因此,处理这种情况是程序员的责任。您可以做的一件事是,将您要设置的日期与当前日期进行比较。如果小于则不要设置它。

关于ios - UILocalNotification 即使日期已过,也会继续触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28078290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com