UIPickerView selected time to run code - swift

I have added in a UIPickerView and currently have it store the selected time as a string. I want the app to carry out a simple line of code when the time that was selected on the pickerview is the time in the real world. Here is the code that I have added.
For the Clock, used to find the real world time:
let clockString: String = formatADate()
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm:ss a"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
Here is the code for the UIPickerView:
#IBOutlet var dateTimeDisplay: UILabel!
#IBOutlet var datePicker: UIDatePicker!
#IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
}
func setDateAndTime() {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
dateTimeDisplay.text = str
}
And here is what I want to happen when the selected time and the real world time match up:
takePhoto = true

When the pick date the start one timer function
call the function in picker
var timercount = Timer()
viewdidload()
{
timercount = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
}
Func Check()
{
let nowdate = NSDate()//two date declare global Var
let date2 = datePicker?.date //chek the Time How Much Time Remain
let elapsed = date2?.timeIntervalSince(nowdate as Date)
if Int(elapsed!) == 0
{
takePhoto = true
}
}

Related

How to send Date and Time separately to backend in swift?

fromDateLabel.text getting date and time from datepicker.. which i need to send date and time seperatedly to backend
when i do DateFormatter date is coming correctly but in time, only two digit values are working means time taking 10, 11, 12 O'Clocks. if i take 1,2,3,4,5 its not working
code: here single digit time not working
var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
fromDate = fromDateArr[0]
fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "dd-MM-yyyy"
formateFromdate = inputFormatter.string(from: showDateFrom!)
print("formate from date \(formateFromdate)")
if i formate date and time like below nothing works
let fromDate = fromDateLabel.text!
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm:ssa"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time")
How to send date and time separately to backend.. with 1 to 12hrs time
NOTE: if its 8 o clock then the out put time should be 08:15, not 8:15.. thats the issue.. please help me with code
Design
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var txtdate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.txtdate.setInputViewDatePicker(target: self, selector: #selector(tapDone)) //1
}
#objc func tapDone() {
if let datePicker = self.txtdate.inputView as? UIDatePicker {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yy, hh:mm a"
self.txtdate.text = dateformatter.string(from: datePicker.date)
}
self.txtdate.resignFirstResponder()
}
#IBAction func showClk(_ sender: Any) {
let fromDate = txtdate.text!
print(fromDate)
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm a"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
let formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
let formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time" ,formateFromTime)
}
}
extension UITextField {
func setInputViewDatePicker(target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))//1
datePicker.datePickerMode = .date
self.inputView = datePicker
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func tapCancel() {
self.resignFirstResponder()
}
}

Printing a timestamp to a label from a button IB Function in Xcode (Swift)

I want to create a time stamp thats triggered to the current time when a button is pressed in one view controller and have it print to a label in another view controller.
Im using Xcode 11 and the most recent version of swift.
I Guess this is the function i have so far but dont know how to implement it to the button or the label I want it printed to:
func getDateDayAndTime(timestamp: NSNumber) -> String {
let date = Date(timeIntervalSince1970: Double(truncating: timestamp)/1000)
let calendar = Calendar.current
if calendar.isDateInToday(date) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "hh:mm a"
let time = dateFormatter.string(from: date)
return time
}else if calendar.isDateInYesterday(date) {
return "Yesterday"
}
else if calendar.isDateInWeekend(date) {
let component = calendar.component(Calendar.Component.weekday, from: date)
return self.getDay(value: component)
} else {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "dd/MM/YY"
let time = dateFormatter.string(from: date)
return time
}
}
We can send the timestamp value from ViewController to SecondViewController as shown below,
import UIKit
class ViewController: UIViewController {
#IBAction func getTimeStampButtonAction(_ sender: Any) {
let timestampVal = NSDate().timeIntervalSince1970
let myTimeInterval = TimeInterval(timestampVal)
let timeStamp = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
let timeStampString = stringFromDate(timeStamp as Date)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let homeView = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
homeView.timeStamp = timeStampString
self.navigationController?.pushViewController(homeView, animated: true)
}
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var TimeStampLabel: UILabel!
var timeStamp: String!
override func viewDidLoad() {
super.viewDidLoad()
TimeStampLabel.text = timeStamp
}
}
Function that returns current time:
func getTodayString() -> String{
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let second = components.second
let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) + " " + String(hour!) + ":" + String(minute!) + ":" + String(second!)
return today_string
}
Button pressed:
#IBAction func buttonPressed(_ sender: Any) {
yourLabel.text = getTodayString()
}

Set Time Default in UIDatePicker

I'm trying to populate a pickerView with a default value (String). Currently I'm able to capture it's value as a time after the user interacts with it, however I'm not able to set the time value before it becomes visible to the user.
I've tried
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
however that errors "Value of type '(UIDatePicker) -> ()' has no member 'setDate'"
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
//my attempt at passing in a string
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
tempTime = (dateFormatter.string(from: sender.date))//successfully captures the user's input value
}
Here's the function that launches the xib (containing the timePicker)
func showSomeDialogue() {
let newVC = SomeViewContoller(nibName: "SomeViewController", bundle: nil)
let popup = PopupDialog(viewController: newVC,
buttonAlignment: .horizontal,
transitionStyle: .bounceUp,
tapGestureDismissal: true,
panGestureDismissal: false)
present(popup, animated: true, completion: nil)
newVC.someDelegate = self as SomeDelegate
}
The xib's class
import UIKit
protocol MealDelegate {
func didCreateMeal(mealTime: String)
}
class SomeViewContoller: UIViewController {
var someDelegate: SomeDelegate!
var tempTime = ""
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
tempTime = (dateFormatter.string(from: sender.date))
}
#IBAction func someSaveBtn(_ sender: UIButton) {
mealDelegate.didCreateMeal(mealTime: tempTime)
self.dismiss(animated: true, completion: nil)
}
}
Add following to your view controller class:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "09:00 AM")
timePicker.date = date
Add the following to your SomeViewController class:
//MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "10:57 PM")
//or whatever date you want to display as default
timePicker.setDate(date, animated: true)
}
Try this,
#IBAction func timePicker(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .dateAndTime
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleTimePicker(sender:)), for: .valueChanged)
}
#objc func handleTimePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "
tempTime = dateFormatter.string(from: sender.date)
// view.endEditing(true)
}

Do not count seconds

I have a UIDatePicker with the mode time. The date picker lets you pick an hour and minute. I need it to remember the hour and minute not the seconds.
When the app is running the date picker will take the hours and minute the user selected and add the seconds from the time you took to the remembered time.
An example when I select 2:00 pm from the UIDatePIcker this is what I get:
2017-03-07 02:00:36 +0000
However i want to either set the seconds to 00 or remove them like this:
2017-03-07 02:00 +0000
2017-03-07 02:00:00 +0000
Here is my code:
#IBOutlet var datePicker: UIDatePicker!
#IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
Check()
let clockString: String = formatADate()
if str == clockString{
takePhoto = true
}
}
func setDateAndTime() {
timercount = Timer.scheduledTimer(timeInterval: 0, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
RunLoop.main.add(timercount, forMode: RunLoopMode.commonModes)
print("setdate ran")
Check()
}
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
func Check(){
let nowdate = NSDate()
let date2 = datePicker?.date
let elapsed = date2?.timeIntervalSince(nowdate as Date)
print(str)
print(Date())
print(datePicker.date)
if Int(elapsed!) == 0{
takePhoto = true
}
Please help
To modify Date, I prefer to use https://github.com/MatthewYork/DateTools.
let dateWithZeroSeconds = Date(year:datePicker.date.year, month:datePicker.date.month, day:datePicker.date.day, hour:datePicker.date.hour, minute:datePicker.date.minute, second:0)
You could also do a similar transform with DateComponents, but DateTools is a very nice wrapper around all of that.

Swift: Run func every minutes

I'm working in swift and want to run a function every minute. I want to update a label with a count down timer with how many minutes left till the next update.
I have a basic version working
if let date = newDate {
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = NSTimeZone.defaultTimeZone()
let string : NSString = formatter.stringFromDate(date)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: date)
let minute = comp.minute
let remaining : Int = 60 - minute
var mins = "s"
if remaining == 1 {
mins = ""
}
self.refreshInLabel.text = "Refreshes at \(string) - \n \(remaining) minute\(mins) remaining "
}
which is updating when i view the page on the app, but i want it to auto update every minutes.
I've looked at NSTimer, i believe it can be done with this (as shown here: How to make a countdown with NSTimer on Swift) but i can't work out how to make it fire on the minute, only after a certain time display
Edit:
I have the following so far
override func viewDidLoad() {
super.viewDidLoad()
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: NSDate())
minute = comp.minute
_ = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(AdoptionCentreVC.updateTimer), userInfo: nil, repeats: true)
}
func updateTimer() {
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: NSDate())
let curMin = comp.minute
if(curMin > minute) {
NSLog("Changed")
self.minute = curMin
}
}
I'd like to know if theres a better way
What I suggest you is to fire a NSNotification when you want to start your func every minute.
When you receive your NSNotification call a function like this :
var yourTimer = NSTimer()
func callWhenNotificationReceived(){
yourFuncToFire()
yourTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(YourViewController.yourFuncToFire) , userInfo: nil, repeats: true)
}
var TotalTime:Int = 0
var timer: NSTimer?
triggerCountDownTimerFor(time:Int)
func triggerCountDownTimerFor(time:Int)
{
totalTime = time
timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(LoginViewController.updateTimer), userInfo: nil, repeats: true)
}
func updateTimer()
{
let date = NSDate()
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = NSTimeZone.defaultTimeZone()
let string : NSString = formatter.stringFromDate(date)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: date)
let minute = comp.minute
let remaining : Int = TotalTime - minute
var mins = "s"
if remaining == 1 {
mins = ""
}
print("Refreshes at \(string) - \n \(remaining) minute\(mins) remaining ")
}