作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我试图在我的应用程序中放置通知,它应该每隔一小时重复一次,但它重复不受监管,需要明确的是,它有时重复 30 分钟,有时重复一小时,有时重复很长时间等等。我在“AppDelegate.swift”中使用的代码:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Notification Repeat
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil))
return true
}
以及我在“ViewController.swift”中使用的代码:
//Notification Repeat
var Time = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Notification Repeat
var Timer = NSTimer.scheduledTimerWithTimeInterval(3600.0, target: self, selector: Selector("activateNotifications"), userInfo: nil, repeats: true)
}
//Notification Repeat
func activateNotifications() {
Time -= 1
if (Time <= 0){
var activateNotifications = UILocalNotification()
activateNotifications.alertAction = “Hey"
activateNotifications.alertBody = “Hello World!"
activateNotifications.fireDate = NSDate(timeIntervalSinceNow: 0)
UIApplication.sharedApplication().scheduleLocalNotification(activateNotifications)
}
}
谁能帮帮我,我哪里弄错了?
最佳答案
您根本不需要计时器。 UILocalNotification
类有一个名为 repeatInterval
的属性正如您所料,设置重复通知的时间间隔。
据此,您可以按以下方式安排每小时重复一次的本地通知:
func viewDidLoad() {
super.viewDidLoad()
var notification = UILocalNotification()
notification.alertBody = "..." // text that will be displayed in the notification
notification.fireDate = NSDate() // right now (when notification will be fired)
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
notification.repeatInterval = NSCalendarUnit.CalendarUnitHour // this line defines the interval at which the notification will be repeated
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
注意:请确保仅在启动通知时执行一次代码,因为它每次执行时都会安排不同的通知。想要更好的理解本地通知,可以阅读Local Notifications in iOS 8 with Swift (Part 1)和 Local Notifications in iOS 8 with Swift (Part 2) .
关于ios - 如何在 iOS 应用程序上放置通知以每隔一 (1) 小时重复一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567984/
我是一名优秀的程序员,十分优秀!