I need to store the date that something was created in the firebase database for a friend request, how can i store a date in firebase that i can work out how long ago since this date something happened. I would just store an NSDate in there but then what about timezones?
I dunno if firebase has something like Parse had where it would store date created and timezone automatically so you could read it from the server?
You need to set it up by yourself !
I use this code to do the timestamp. Hope this is what u want.
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy/MM/dd, H:mm:ss"
let defaultTimeZoneStr = formatter.stringFromDate(NSDate())
let post = ["\(key)":["username": username, "userPhoto": userPhotoUrl, "postPhoto": downLoadURL,"postText": postText!,"User":FIRAuth.auth()!.currentUser!.uid, "time":defaultTimeZoneStr] ]
self.DatabaseRef.child("posts").updateChildValues(post)
Related
I am learning swift on my own and I cannot seem to figure out how to implement the extension below. I have an app on the App Store with a functioning IAP. But I now need to indicate the price in the local currency and not simply in US$ before the user clicks the button to buy.
I have read numerous posts about using an extension similar to the one below. However, I have been unable to get the cost to display as a String I can put in a label.
extension SKProduct {
/// - returns: The cost of the product formatted in the local currency.
var regularPrice: String? {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = self.priceLocale
return formatter.string(from: self.price)
}}
Among the methods I tried were:
label = SKProduct.regularPrice
label = product.regularPrice
I tried putting in my product ID ("com.afafaf.2323") but none of the attempts worked.
Yes, this is similar to some other posts, but none of them explain the implemtation to the extent I need.
I am clearly missing something easy, but I am not seeing it. Can someone please just show me how to use this extension properly?
I want to set count down timer in swift. I have an option is to get current time is Date() but this method is giving wrong date time when my device time set wrong.
Is it possible to get exact current UTC time in swift, so I will set count down timer with exact time remaining.
Thanks.
The Date class doesn't have a timezone, it's just a "point int the time line" that's the same for all the timezones. When you use a DateFormatter to convert a date to a string (or a string to a date) you can specify the timezone like this:
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
If you cannot trust the device date you will have to use a NTP service like this:
https://github.com/instacart/TrueTime.swift
https://github.com/jbenet/ios-ntp
Get Date and Time from Apple Server
Many times, I have faced the same issue if the user changed his current time then lot's of logic will disturb, Unfortunately, no luck because of Date() always returns your device date.
In well-known game Candy crush, We can not play it for a specific time if my points got over, But if I change device time to feature time then everything will be unlocked. This is the best example of your problem.
You can use below-given web service or your web service to achieve your requirements. Below are some
free API's which provides date and time.
Geonames
Timezonedb
TrueTime
In addition to other answers, you can write an extension for Date class to get formatted Data in specific TimeZone to make it as utility function for future use. Like
extension Date {
func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String {
let dtf = DateFormatter()
dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
dtf.dateFormat = dateFormat
return dtf.string(from: self)
}
}
Now you can call it like
Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");
Had a very unusual bug with a handful of our users (less than 10 known out of thousands). Some of the objects that we store in coreData use date types. For some reason, on a specific person's device, some objects would fail during initialization whenever the JSON tried to map the dateString to our formatter.
static let iso8601DateTime: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)[enter image description here][1]
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
When I made a breakpoint, all JSON time strings came in this format:
I was puzzled why some objects were successfully mapping at that point and others failed despite all of them returning in that format. By change, I read an issue on Apple's support website about language & region with ISO8601. I changed his region from US -> UK -> (back to) US, and found that all of the issues were resolved and He was able to use the application as normal.
Some advice I received said to specify a locale for the dateformatter, but I haven't been able to test yet.
formatter.locale = Locale(identifier: "en_US_POSIX")
Any idea why basically soft-refreshing this setting resolved it (setting to another and then back again)?
Few days ago, I just updated my firebase pod to the latest version, and in my debugging area, I got message that said that I have to update from timestamp data type to Date (something like that, I forget actually).
and I also have to change the DB settings like below
let db = Firestore.firestore()
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings
after add the code above, the error message in my debugging area in Xcode disappears.
As far as I remember, I also had to change the data type in my client from Timestamp to Date data type, I haven't changed this because the error message in my debugging area in Xcode have disappeared.
As a result, I get not correct Date in my app.
Could you please share again the conversion step from TimeStamp to Date ? because as far as I remember I had to do some steps to follow. I can't find it in the firebase documentation.
Thank you very much :)
This is the message from the debugger
The behavior for system Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:
let db = Firestore.firestore()
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings
With this change, timestamps stored in Cloud Firestore will be read back as Firebase Timestamp objects instead of as system Date objects. So you will also need to update code expecting a Date to instead expect a Timestamp. For example:
// old:
let date: Date = documentSnapshot.get("created_at") as! Date
// new:
let timestamp: Timestamp = documentSnapshot.get("created_at") as! Timestamp
let date: Date = timestamp.dateValue()
Please audit all existing usages of Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK.
In my application I have a static gregorian property in SharedCalendar class that is defined like this:
static let gregorian: Calendar = {
var calendar = Foundation.Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
return calendar
}()
When I want to access a day of some date in specific time zone I am calling:
SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day!
Let's say someDate is Date(timeIntervalSinceReferenceDate: 512658000.0) which is 2017-03-31 13:00:00 +0000.
When I start the app in Vancouver time zone the SharedCalendar.gregorian.timeZone property has value America/Vancouver (autoupdatingCurrent) and the result of SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day! is 31 which is correct.
When I put the application to background and switch the time zone to Sydney and run the app again the SharedCalendar.gregorian.timeZone property has value Australia/Sydney (autoupdatingCurrent) (which is correct), but the result of SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day! is 31 which is wrong (should be 1).
When I change the definition of gregorian property to be a var:
var gregorian: Calendar {
var calendar = Foundation.Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
return calendar
}
Everything works properly, which is for America/Vancouver (autoupdatingCurrent) I get 31, and for Australia/Sydney (autoupdatingCurrent) I get 1.
Right now I don't quite understand how TimeZone.autoupdatingCurrent is working. When device's time zone changes the SharedCalendar.gregorian.timeZone reflects the device's time zone, but it looks like SharedCalendar.gregorian is somehow using the old time zone.
Does anyone have explanation of this behaviour?
I reported radar regarding this issue and today Apple responded:
The reason that your static let calendar’s time zone doesn’t update is that you need to issue a call to NSTimeZone.resetSystemTimeZone() to sync up with the system time zone. See the documentation for NSTimeZone.resetSystemTimeZone() for more info: https://developer.apple.com/documentation/foundation/nstimezone/1387189-resetsystemtimezone?language=objc
The reason your var calendar works is because every call to the calendar property actually creates a new computed calendar, which happens to be set to a new time zone representing the current system time zone.
This makes sense, because static let caches system's time zone, and from documentation for NSTimeZone.resetSystemTimeZone we can read:
If the application has cached the system time zone, this method clears that cached object. If you subsequently invoke systemTimeZone, NSTimeZone will attempt to redetermine the system time zone and a new object will be created and cached (see systemTimeZone).