Search code examples
iosswift4xcode10

Unlock Content based on Day (iOS App with Xcode)


I am trying to get create an app where you can unlock a certain picture every day throughout the month of December, like an advent calendar.

So if the user is pressing the button for a certain day (all days have a button with their date on) the app shall compare the current date on the device to the unlock date. For example:

If the user is pressing the button for the 01.12.18 (dd.MM.yy) and it currently ist that day or any day later it shall display picture number one. Else: (if the day isn't reached yet) the user shall see another picture, that says sth. like "You're too early! Please wait some more."

Any suggestions or example codes are very appreciated!

The prototype of the code looks like this:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBOutlet weak var dailyContent: UIImageView!

@IBAction func türchen1Button(_ sender: Any) {

    // if 01.12.18 (dd.MM.yy) is today or past today
    //      dailyContent.image = picture1
    //
    // else if 01.12.18 (dd.MM.yy) is in the future
    //      dailyContent.image = pictureTooEarly
   }
}

This app shall be a present for my girlfriend and I appreciate every help! Thank you in advance! Benjamin


Solution

    • Assign the tags 1 - 24 to the buttons which represent the days.
    • Use one IBAction and connect all buttons to this action.

      @IBAction func türchenButton(_ sender: UIButton) { 
      
    • In the body of the action get the current year and create a date of the corresponding button and check if the date is in the future

          let now = Date()
          let calendar = Calendar.current
          let currentYear = calendar.component(.year, from: now)
          let türchenComponents = DateComponents(year: currentYear, month: 12, day: sender.tag)
          let türchenDay = calendar.date(from: türchenComponents)!
          if calendar.compare(türchenDay, to: now, toGranularity: .day) == .orderedDescending {
              // is in the future
              dailyContent.image = pictureTooEarly
          } else {
              // is today or past today
              dailyContent.image = picture1
          }
      }