StevenZ
StevenZ

Reputation: 7123

Execute Function Based On time

I have a UIImage that I would like to display based on the time of. For example between the hours of 9 AM and 5 PM I would like to display a image that says "open", and the rest of the time "closed". How can I accomplish this using SWIFT.

Goals:

Upvotes: 0

Views: 236

Answers (2)

A.J. Hernandez
A.J. Hernandez

Reputation: 968

For Swift 2

Place the following below your class:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()

Place this in your viewDidLoad:

let components = calendar.components(.Hour, fromDate: date)
let hour = components.hour

if(hour >= 9 && hour <= 17) {

    // set your image 'open image'
    print("Open")

}
else {

    // set your image 'close image'
    print("Closed")

}

Upvotes: 1

Arun Kumar
Arun Kumar

Reputation: 798

Use these lines of code

I hope you will get the things , you are looking for

 let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour, fromDate: date)
    let hour = components.hour


    if(hour >= 9 && hour <= 17)
    {
        //set your image 'open image'
        println("Open")
    }
    else{
         //set your image 'close image'
        println("closed")
    }

Upvotes: 2

Related Questions