我试图在我的应用程序中发送通知,它应该每隔一小时重复一次,但它重复不受管制,要清楚,它有时会重复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)
}
}
有人帮助我,我犯了错误吗?
答案 0 :(得分:3)
你根本不需要计时器。 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)。