Hos Ap
Hos Ap

Reputation: 1198

change background on different times of Day - iOS

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

Answers (1)

Rashwan L
Rashwan L

Reputation: 38833

You can do it like this:

  1. Create extensions to parse out the time
  2. Use the extension to get the time only
  3. Make your controls and change the background image

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

Related Questions