我尝试将通知放入我的应用程序,该通知本应每隔一小时重复一次,但是重复进行得不受监管,要清楚,有时会重复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)

08-26 03:57
查看更多