Formatting stopwatch's time in Swift
I'm trying to solve my problem with stopwatch. Every 10 seconds it's not zero at he end in seconds and no + 1minute after 60 seconds. time format should be m:ss (0:00). Start and Stop are same buttons in my app. Can u help me?
var timer: Timer?
var isStarted = false
var counter = 0.00
@objc func updateTimeLabel() {
counter += 0.01
timerLabel.text = String(round(counter*1000)/1000)
}
@IBAction func startStopButtonDidTouch(_ sender: UIButton) {
if isStarted { //When tapped STOP
timer?.invalidate()
isStarted = false
locationManager.stopUpdatingLocation()
startStopButton.setTitle("START", for: .normal)
} else { //When tapped START
locationManager.startUpdatingLocation()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
isStarted = true
startStopButton.setTitle("STOP", for: .normal)
}
}
1 answer
-
answered 2020-11-20 14:53
vadian
There is a date formatter to display time intervals as date components
var counter : TimeInterval = 0 let dateFormatter : DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.minute, .second] formatter.zeroFormattingBehavior = .pad return formatter }() @objc func updateTimeLabel() { counter += 1 timerLabel.text = dateFormatter.string(from: counter)! }
See also questions close to this topic
- Does apple allow Sub4Sub apps in the app store?
-
How do I format an empty (NDEFFormatable) NFC Tag to NDEF format?
I'm trying to write NDEF message to an empty DESfire v2 card. I tried this code:
guard case .miFare(let miFare) = tag else {continue} session.connect(to: tag) { [weak self] error in if let _ = error { return } let data = "test data".data(using: .utf8)! let payload = NFCNDEFPayload.init(format: .unknown, type: "T".data(using: .utf8)!, identifier: Data.init(count: 0), payload: data, chunkSize: 0) let message = NFCNDEFMessage(records: [payload]) let apdu = NFCISO7816APDU(instructionClass: 0, instructionCode: 0x1B, p1Parameter: 0, p2Parameter: 0, data: Data(), expectedResponseLength: 16) miFare.sendMiFareISO7816Command(apdu) { (apduData, sw1, sw2, error) in print("\(error)") miFare.writeNDEF(message) {[weak self] error in if let localError = error { print(localError) return } else { print("ok") } } } }
but I've got an error because it's not NDEF formatted:
Error Domain=NFCError Code=401 "Stack Error" UserInfo={NSLocalizedDescription=Stack Error, NSUnderlyingError=0x283fc2040 {Error Domain=nfcd Code=37 "Tag Not NDEF formatted" UserInfo={NSLocalizedDescription=Tag Not NDEF formatted}}}
Is there any way to format this card to NDEF format using Apple's CoreNFC?
-
Save Data Offline Then Automatically Upload It To Firestore Upon Connection - Swift Xcode
I'm creating an app that allows the user to create a project, take photos and create labels in that project (using structs), then create a PDF later on. I've got to figure out how to save this data without connection, then backup it up to the server later. I want the app to be able to work both online and offline - whether the user has cell service or not. I've seen many apps where when you load them up, if you have no signal, you can select "Run Offline" or "Continue Offline."
How should I save the data locally until the user comes back into cellular signal and the data can be backed up to Firebase Firestore and Storage? I was considering using UserDefaults to save the data in a cache essentially, then whenever the phone is back within signal, the app automatically runs through this cache and backs everything up to the server. Is this the correct way to accomplish what I'm needing done? Is there a better way?
In the end, the data MUST be able to be saved whether connected to the internet or not - online or offline. I just need to figure out the best way to save the data until it can be uploaded to the server when back online. I want the data the user is creating to be safe in case something happened to the phone or to the app (maybe their phone shut off or there was a random app crash). By the way, the app is project based... so there's multiple files (projects) in other words. They may need to set up multiple files (projects) while offline and access one of them later on while still offline. It needs to put all of these offline projects in a container to be automatically backed up to the server upon returning to signal. These files (projects), with all the data in them, MUST be safe at all times until backed up - even if the user closes the app.
Please leave a detailed answer. I'm a beginner, as you can tell, and need specifics. If you reference a certain way of doing something, kindly leave a link to a tutorial or significant documentation, or explain it thoroughly.
Thanks!
Christian
-
SwiftUI: Type 'Timer' has no member 'publish'
does anybody know why my Timer has no member called 'publish'?
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
XCode tells me:
- Cannot infer contextual base in reference to member 'common'
- Cannot infer contextual base in reference to member 'main'
- Type 'Timer' has no member 'publish'
Thanks for your help!!
import SwiftUI let defaultTimeRemaining: CGFloat = 10 let lineWidth: CGFloat = 30 let radius: CGFloat = 70 struct Timer: View { @State private var isActive = false @State private var timeRemaining: CGFloat = defaultTimeRemaining @State private var timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect() var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } struct Timer_Previews: PreviewProvider { static var previews: some View { Timer() } }
-
How do I reward the user daily?
I want to reward the user daily in my app, but when the app closes the timer always stops
I've tried doing this...
Timer.scheduledTimer(withTimeInterval: 86400, repeats: true) { _ in self.points += 100 }
Can you please tell me how to reward the user daily once?
-
How to restart timer at the onPress in react native
I have made a small functionality for timer, where a timer will countdown from
10
. When it reaches0
, the timer will hide, and a restart button will come at that place. Till this far, I am able to do it.But I wanted to restart the timer when
Restart
appears after countdown is completed.Below is the code:
constructor(props) { super(props); this.state = { timer: 10, displayButton: 'none', displayTime: 'flex' }; } componentDidMount() { this.clockCall = setInterval(() => { this.decrementClock(); }, 1000); } decrementClock = () => { this.setState( (prevState) => ({timer: prevState.timer - 1}), () => { if (this.state.timer === 0) { this.setState({ displayTime: "none", displayButton: "flex" }) } }, ); }; restartButton() { this.setState({ displayTime: "flex", displayButton: "none", timer: 30, }) } <Text style={{display: this.state.displayTime}}>{this.state.timer}</Text> <TouchableOpacity onPress={this.restartButton}> <Text style={{display:this.state.displayButton}}>Restart</Text> </TouchableOpacity>
As you can see,
Restart
appears when countdown is finished, But when I click onRestart
it is showing me error:Cannot read property 'setState' of undefined
. -
How do I convert a JSON DateTime format to a C# DateTime format from an API call
I'm currently building a project that retrieves API data and saves it into a database. Everything is working fine except for the DateTime values in the API. I have a class that uses RestSharp to obtain the API data then it uses NewtonSoft.Json to derserialize the API data into a JSON format which is then stored into a temporary DTO class file. Here is the API method.
public static void getAllRequestData() { var client = new RestClient("[My API URL]"); var request = new RestRequest(); var response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { string rawResponse = response.Content; AllRequests.Rootobject result = JsonConvert.DeserializeObject<AllRequests.Rootobject>(rawResponse); } }
Now here is the DTO file (AllRequests) that will temporarily store the Converted JSON data.
public class AllRequests { public class Rootobject { public Operation Operation { get; set; } } public class Operation { public Result Result { get; set; } public Detail[] Details { get; set; } } public class Result { public string Message { get; set; } public string Status { get; set; } } public class Detail { [Key] public int Id { get; set; } public string Requester { get; set; } public string WorkOrderId { get; set; } public string AccountName { get; set; } public string CreatedBy { get; set; } public string Subject { get; set; } public string Technician { get; set; } public string IsOverDue { get; set; } public string DueByTime { get; set; } public string Priority { get; set; } public string CreatedTime { get; set; } public string IgnoreRequest { get; set; } public string Status { get; set; } } }
The lines of code in Details that I want to be DateTime formats are "DueByTime" and "CreatedTime" instead of being String values. Currently they're only holding JSON format DateTime values in a String such as "1477394860065".
I've tried making "public string CreatedTime { get; set; }" to "public DateTime CreatedTime { get; set; }" However that only returned an error since it's JSON format. How could I rectify this issue so that it's stored in the DTO correctly in a DateTime format? Because ideally I want to scaffold this class file into a table so it can hold data in a database.
For more context to this, here's what I want rectified in my Database.
I want there to be a DateTime shown instead of a long list of numbers like there is here under Createby and DueBy.
Any help would be appreciated.
-
How this "2020-12-31T02:00:00+05:30" string response be convert to 31/12/2020, 02:00 pm in Android Studio?
I am calling a soap webservice and in response I am getting a date, which in the format of "2020-12-31T02:00:00+05:30".
I want to convert it and display it as "31/12/2020, 02:00 AM". How can I do it?
I have tried the below code, but it return's null.
String pattern = "yyyy-MM-dd'T'HH:mm:ss z"; SimpleDateFormat format = new SimpleDateFormat(pattern); try { startDate= format.parse(eventStartDate); } catch (ParseException e) { e.printStackTrace(); }
Any help would be appreciated. Thanks
-
How do I set the tick marks for the end of the month in Matplotlib
I have a list of dates that fall on the end of each month, and I would like for the gridlines and labels of my plot to coincide with these dates. Currently I can only get the chart to plot at the beginning of the month. Is there a way to force Matplotlib to use the end of month values in its charting?
import matplotlib.pyplot as plt from datetime import datetime from matplotlib.dates import MonthLocator from matplotlib.dates import DateFormatter dts = [datetime(2020, 11, 30), datetime(2020, 12, 31), datetime(2021, 1, 31), datetime(2021, 2, 28), datetime(2021, 3, 31), datetime(2021, 4, 30), datetime(2021, 5, 31), datetime(2021, 6, 30), datetime(2021, 7, 31), datetime(2021, 8, 31), datetime(2021, 9, 30), datetime(2021, 10, 31), datetime(2021, 11, 30), datetime(2021, 12, 31), datetime(2022, 1, 31), datetime(2022, 2, 28),] vals = [2000, 2500, 3000, 4000, 4500, 4000, 3000, 2500, 4000, 4500, 3000, 2500, 6000, 4000, 3000, 5000] figsize=(3, 6) fig, ax = plt.subplots(figsize=figsize) ax.xaxis.set_major_locator(MonthLocator((3, 6, 9, 12))) fmt = DateFormatter("%Y-%m") ax.xaxis.set_major_formatter(fmt) ax.plot(dts, vals, color = 'blue') ax.grid(True) plt.show()
-
How to make Stopwatch in php
I created a method in php like this:`
function start(){ echo"Stopwatch has started.<br/>"; $this->startTime = mktime(date("H"), date("s"), date("m"), date("d"), date("Y")); $_SESSION["time"] = $this->starTime; } function stop(){ echo"stopwatch stopped. <br/>"; $this->endTime = mktime(date("H")-1, date("s"), date("m"), date("d"), date("Y")); echo"<b>Time Elapsed: </b>, date('H:i:s', $this->endTime-$_SESSION['time'])"; }
} `
my goal is to ask the stopwatch about the duration between start and stop. I have to show the duration, then I could use the stop watch multiple times, where the duration value each time I make it stop and start should be calculated properly. Can someone help me?
-
Excel VBA Stopwatch breaking at midnight
I have a worksheet which I use to track progress recording audiobooks (I'm a narrator). On each sheet, I have a timer that I use to track how many hours I record each day/session.
If the timer is running at midnight, it sets the timer to 20:00:00 and keeps going. I often am recording at midnight, so this is a major issue if I don't remember to stop the timer before midnight and restart it after.
Here is a link to the whole Excel file. You can find the timer in the TEMPLATE worksheet. The Macros for the timer are within Module1.
http://recording-tracker.narratedby.me
Here is all the code:
Option Explicit Dim NextTick As Date, t As Date, PreviousTimerValue As Date, strSheetName As String, lRowTime As Long, lRowDate As Date, CurrentTimerValue As Date, StartTimerValue As Date Sub StartTime() strSheetName = ActiveSheet.Name StartTimerValue = PreviousTimerValue CurrentTimerValue = PreviousTimerValue t = Time Call ExcelstrSheetName End Sub Private Sub ExcelstrSheetName() strSheetName = ActiveSheet.Name ThisWorkbook.Worksheets(strSheetName).Range("Q1").Value = Format(Time - t + PreviousTimerValue, "hh:mm:ss") NextTick = Now + TimeValue("00:00:01") Application.OnTime NextTick, "ExcelstrSheetName" End Sub Sub StopClock() strSheetName = ActiveSheet.Name On Error Resume Next Application.OnTime earliesttime:=NextTick, procedure:="ExcelstrSheetName", schedule:=False CurrentTimerValue = ThisWorkbook.Worksheets(strSheetName).Range("Q1").Value End Sub Sub Reset() strSheetName = ActiveSheet.Name CurrentTimerValue = ThisWorkbook.Worksheets(strSheetName).Range("Q1").Value On Error Resume Next Application.OnTime earliesttime:=NextTick, procedure:="ExcelstrSheetName", schedule:=False ThisWorkbook.Worksheets(strSheetName).Range("Q1").Value = 0 End Sub
The cell Q1 is what holds the timer value at any given time.
I have removed other Subs and portions of these Subs which are irrelevant to my question. This is the basic stopwatch function.
Any help is much appreciated!
-
Basic time intervals are inconsistent here
Simple question: Why are the intervals inconsistent?
(This is just a basic test to indicate 3.000 second intervals, yet running on the cmd prompt shows variations between 3.001 to 3.020. On a 2.2 ghz processor, this delay seems unreasonable. What am I missing?)
import time import random from graphics import * def main(): print("Press Enter to start & CTRL+C to exit.") while True: try: start=time.time() time.sleep(3.000) interval=time.time() print("Total time:", round(abs(interval-start),3),"second interval") except KeyboardInterrupt: break main()
-
Change format time/clockpicker php
I use a clock / timepicker plugin that generates the time format 00:00, but on my db it uses the data type "time" with the format 00:00:00, I have tried this code
$WAKTU_ACARA = $_POST['WAKTU_ACARA']; $time = DateTime::createFromFormat('h:i', $WAKTU_ACARA); $time->format('h:i:s');
and this
$time = new DateTime($WAKTU_ACARA); $time->format('h:i A');
but format has not changed, please help
-
Python import data from csv with pandas that is shown as mm:ss,0 but when checked with excel can show hh:mm:ss
I have a problem with a dataset that I need to solve.
The dataset is from a program that gives an output file with the time column formatted as a custom format "mm:ss,0" this format is typically used for milliseconds.
However for my needs this is not as important as the hour which I so far cannot extract.
Viewing the cell in excel, the hour data is present as shown below. Example of data
My code needs to run on python but the exact method for import can vary. I've tried searching for a solution but there seems to be no one that has faced the same problem.
Do let me know if there are any possible methods that exist to import this data.
PS: opening the csv with Notepad++ will only show the mm:ss.0 so I question if the data is even there.
PPS: This is the code that I am using to import the csv, noting else is currently being applied to the date import.
temp = pd.read_csv(filename, index_col=None, header=0, sep='\t', encoding='utf-16')
-
Customizing Timelion legend time format
Is it possible to customize the time format in the legend of Timelion? I've been looking on different websites, but didn't found an appropriate solution.
Something like
DD-MM-YYYY
or%d-%m-%Y
would be perfect.Thanks in advance.