Reputation: 1198
I have a background in all of my entire app(all view controllers) and I want to change it based on time of the day. If time is 6:00 AM, I wanna show "background one" and if it is more than 9:00 PM , "background two" should be displayed. I'm thinking of using NSTimer to check whether the current time is more than defined times or not. For changing background, I'm thinking of using Extension for UIViewController. If there's a better solution, it would be appreciated to share.
Upvotes: 1
Views: 1308
Reputation: 38833
You can do it like this:
Code example, checkout the comments for explanations:
import UIKit
extension Date {
var hour: Int { return Calendar.current.component(.hour, from: self) } // get hour only from Date
}
class ViewController: UIViewController {
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Declare an observer for UIApplicationDidBecomeActive
NotificationCenter.default.addObserver(self, selector: #selector(scheduleTimer), name: .UIApplicationDidBecomeActive, object: nil)
// change the background each time the view is opened
changeBackground()
}
func scheduleTimer() {
// schedule the timer
timer = Timer(fireAt: Calendar.current.nextDate(after: Date(), matching: DateComponents(hour: 6..<21 ~= Date().hour ? 21 : 6), matchingPolicy: .nextTime)!, interval: 0, target: self, selector: #selector(changeBackground), userInfo: nil, repeats: false)
print(timer.fireDate)
RunLoop.main.add(timer, forMode: .commonModes)
print("new background chenge scheduled at:", timer.fireDate.description(with: .current))
}
func changeBackground(){
// check if day or night shift
self.view.backgroundColor = 6..<21 ~= Date().hour ? .yellow : .black
// schedule the timer
scheduleTimer()
}
}
Upvotes: 5