Do Something Every X Minutes in Swift

Do something every x minutes in Swift

var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector("sayHello"), userInfo: nil, repeats: true)

func sayHello()
{
NSLog("hello World")
}

Remember to import Foundation.

Swift 4:

 var helloWorldTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(ViewController.sayHello), userInfo: nil, repeats: true)

@objc func sayHello()
{
NSLog("hello World")
}

Repeat some action every x minutes between A a.m. and B p.m

There is a repeat feature.

From Apple's documentation:

let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey:
"Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey:
"Hello_message_body", arguments: nil)

// Deliver the notification in five seconds and repeat it
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,
repeats: true)

// Schedule the notification.
let request = UNNotificationRequest(identifier: "60_seconds", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)

Edit:

As also written in the documentation, you certainly have to have user permissions to post notifications:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization
}

Result:

Notification is posted every minute:

Sample Image

How do I schedule a notification at a specific time, and then repeat it every x amount of time?

From what I know it's not possible to repeat a notification every X seconds (or something else) after a specific date.

I think the "best" option here is to use UNCalendarNotificationTrigger instead and schedule 60/5 = 12 notification (so 1 every 5 seconds) starting from the given date.

Something like this:

// this is your reference date - here it's now + 5 seconds just for this example
var referenceDate = Calendar.current.date(byAdding: .second, value: 5, to: Date())!
for i in 0...11 { // one every 5 seconds, so total = 12
let content = UNMutableNotificationContent()
content.title = "Notif \(i)"
content.body = "Body"

var dateComponents = DateComponents(calendar: Calendar.current)
// 5 seconds interval here but you can set whatever you want, for hours, minutes, etc.
dateComponents.second = 5
//dateComponents.hour = X
// [...]

guard let nextTriggerDate = dateComponents.calendar?.date(byAdding: dateComponents, to: referenceDate),
let nextTriggerDateCompnents = dateComponents.calendar?.dateComponents([.second], from: nextTriggerDate) else {
return
}
referenceDate = nextTriggerDate

print(nextTriggerDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: nextTriggerDateCompnents, repeats: true)
let request = UNNotificationRequest(identifier: "notif-\(i)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}

Now based on that, you would need to handle when a user taps one of the notifications in order to cancel all the others. But that's another topic here and I leave it up to you to find the logic for that.

iOS 10 - Repeating notifications every x minutes

After searching around quite a bit, I've come to the conclusion that Swift 3, at this point, doesn't support this feature. For everyone looking for this functionality, I'd suggest using UILocalNotification for now (although deprecated in iOS 10), but later migrate to UNUserNotification once it supports this feature. Here are some additional questions and resources that have helped me to reach this conclusion. Also, please follow all the answers and comments in this thread to get more insight into which particular scenario it talks about.

  • It is usually a bad idea to use deprecated APIs. As a general practice, migrate to new APIs as soon as possible. The above solution is NOT recommended as a permanent solution.

Local Notification every 2 week

http://useyourloaf.com/blog/local-notifications-with-ios-10/

https://github.com/lionheart/openradar-mirror/issues/14941

How to execute a method every second on a background thread so it doesn't affect the performance of the app

Use Grand Central Dispatch :

DispatchQueue.global(qos: .background).async {
getDatabaseInfo()
}

How do I do something every n-th attempt?

This can be solved using maths. You just need to decide whether gamesPlayedSaved is a multiple of 10. To do this, find the remainder of gamesPlayedSaved / 10 using the modulo operator % and check if it is 0:

if gamesPlayedSaved % 10 == 0 && gamesPlayedSaved > 0 {
// show pop up
}

Alternatively, reset the counter every time it reaches 10:

if gamesPlayedSaved == 10 {
// show pop up
gamesPlayedSaved = 0
}


Related Topics



Leave a reply



Submit