How to reset some NSUserDefaults everyday at 00:00
Ex.
if Time = 00:00/New day
{
NSUserDefaults.standardUserDefaults().removeObjectForKey("Data")
}
I suggest you to wrap NSUserDefaults into a Dao: it will perform the logic you need retrieving the saved data or resetting the data.
1: Adding isToday to NSDate
First of all let's add a property to NSDate
extension NSDate {
var isToday: Bool {
let unitFlags : NSCalendarUnit = [.Year, .Month, .Day]
let componentsSelf = NSCalendar.currentCalendar().components(unitFlags, fromDate: self)
let componentsNow = NSCalendar.currentCalendar().components(unitFlags, fromDate: NSDate())
return (componentsSelf.year,componentsSelf.month, componentsSelf.day) == (componentsNow.year,componentsNow.month, componentsNow.day)
}
}
2: The Dao for NSUserDefaults
class UserDefaultsDao {
static let sharedInstance = UserDefaultsDao()
private var storage: NSUserDefaults { return NSUserDefaults.standardUserDefaults() }
var data: String? {
set {
storage.setObject(newValue, forKey: "data")
storage.setObject(NSDate(), forKey: "lastSet")
}
get {
guard let lastSet = storage.objectForKey("dastSet") as? NSDate where lastSet.isToday else {
storage.removeObjectForKey("data")
return nil
}
return storage.objectForKey("data") as? String
}
}
}
3: Usage
This is how you save your data
UserDefaultsDao.sharedInstance.data = "hello world"
And this is how you print it
print(UserDefaultsDao.sharedInstance.data)
Since NSUserDefaults does NOT work properly in Playground, you should test this on a real project.
Related
So i have created a class for a Day and for a Drink. and I'm trying to track how much you drink in a day, but I'm struggling with saving multiple days. I'm currently managing to save the current day(with the amount drunk that day) but i don't know how to save more than one day.
I want to save an array of type Day with all the days. how can i do this?
This is my Day class:
public class Day: NSObject {
var date: Date
var goalAmount: Drink
var consumedAmount: Drink
func saveDay() {
let formatting = DateFormatter()
formatting.dateFormat = "EEEE - dd/mm/yy"
UserDefaults.standard.set(formatting.string(from: date), forKey: "date")
UserDefaults.standard.set(goalAmount.amountOfDrink, forKey: "goal")
UserDefaults.standard.set(consumedAmount.amountOfDrink, forKey: "consumed")
}
func loadDay() {
let rawDate = UserDefaults.standard.value(forKey: "date") as? String ?? ""
let formatter = DateFormatter()
formatter.dateFormat = "EEEE - dd/mm/yy"
date = formatter.date(from: rawDate)!
goalAmount.amountOfDrink = UserDefaults.standard.float(forKey: "goal")
consumedAmount.amountOfDrink = UserDefaults.standard.float(forKey: "consumed")
}
}
This is my Drink class:
class Drink: NSObject {
var typeOfDrink: String
var amountOfDrink: Float
}
i am calling saveDay() when there are any changes made to the day, and then loadDay() when the app opens.
A better approach would be is to store the object of the class in userDefaults instead of storing particular properties of that class. And use [Date] instead of Date to save multiple days
For this first, you have Serialize the object to store in userDefaults and Deserialize to fetch the data from userDefaults.
import Foundation
class Day: Codable {
var date = Date()
var goalAmount: Drink
var consumedAmount: Drink
init(date: Date, goalAmount: Drink,consumedAmount: Drink ) {
self.date = date
self.goalAmount = goalAmount
self.consumedAmount = consumedAmount
}
static func saveDay(_ day : [Day]) {
do {
let object = try JSONEncoder().encode(day)
UserDefaults.standard.set(object, forKey: "days")
} catch {
print(error)
}
}
static func loadDay() {
let decoder = JSONDecoder()
if let object = UserDefaults.standard.value(forKey: "days") as? Data {
do {
let days = try decoder.decode([Day].self, from: object)
for day in days {
print("Date - ", day.date)
print("Goal Amount - ", day.goalAmount)
print("Consumed Amount - ",day.consumedAmount)
print("----------------------------------------------")
}
} catch {
print(error)
}
} else {
print("unable to fetch the data from day key in user defaults")
}
}
}
class Drink: Codable {
var typeOfDrink: String
var amountOfDrink: Float
init(typeOfDrink: String,amountOfDrink: Float ) {
self.typeOfDrink = typeOfDrink
self.amountOfDrink = amountOfDrink
}
}
Use saveAndGet() method to store and fetch details from userDefaults
func saveAndGet() {
// use any formats to format the dates
let date = Date()
let goalAmount = Drink(typeOfDrink: "Water", amountOfDrink: 5.0)
let consumedAmount = Drink(typeOfDrink: "Water", amountOfDrink: 3.0)
let day1 = Day(date: date, goalAmount: goalAmount, consumedAmount: consumedAmount)
let day2 = Day(date: date, goalAmount: goalAmount, consumedAmount: consumedAmount)
let day3 = Day(date: date, goalAmount: goalAmount, consumedAmount: consumedAmount)
let day4 = Day(date: date, goalAmount: goalAmount, consumedAmount: consumedAmount)
let days = [day1, day2, day3, day4]
Day.saveDay(days)
Day.loadDay()
}
1) You need to create array of object for this :
goalAmount = [Drink]()
var date = [Date]()
and append with each new element.
you can also add date variable inside your drink class.
2) you can also create array of dictionary:
var userData = [String : Any]()
key will be you date and Any contain related to drink data in Any you can store Anything.
I have an array of Person. The Person object has many fields between them inscriptionDate (a timestamp). I have to create a collectionView from this array but using sections. Every section has a header that is inscriptionDate as a date having this format dd/mm/yyyy. I have to sort the array by inscriptionDate but without time (only the format dd/mm/yyyy) in order to load the data in the collectionView (taking into consideration the sections). I have found from another question this solution. But how can I sort the array before doing this? How can I use this:
order = NSCalendar.currentCalendar().compareDate(now, toDate: olderDate,
toUnitGranularity: .Day)
in my case?
I agree with #Vasilii Muravev, you will need to clean your timestamp object first, either using extensions or functions. Timestamp isn't a valid Swift object btw, unless that is a custom class you created.
Then you can create a dictionary for your dataSource. I will use #Vasilii Muravev's extension:
//var myKeys : [Date] = []
let sortedPeople = persons.sorted { $0.inscriptionDate.noTime() < $1.inscriptionDate.noTime() }
//break your array into a dictionary([Date : [Person]])
//personsSortedByDateInSections : [Date : [Person]] = [:]
for person in sortedPeople {
if personsSortedByDateInSections[person.inscriptionDate] != nil {
personsSortedByDateInSections[person.inscriptionDate]!.append(person)
} else {
personsSortedByDateInSections[person.inscriptionDate] = [person]
}
}
myKeys = setKeyArray(personSortedByDateInSections.keys)
that will give you a dictionary object with all of your Person objects grouped(sectioned) by their inscriptionDate. Then you will just need to fill out your collectionView delegate and datasource methods.
override func numberOfSections(in: UICollectionView) -> Int {
return myKeys.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return personsSortedByDateInSections[myKeys[section]].count
}
UPDATE:
As stated in your comment there is a issue with grabbing a array of the keys with swift dictionaries(I don't think swift dictionaries had this issue in earlier version? I could be wrong)....anyway to workaround this I have used this function to set a class variable for the 'keyArray'.:
fileprivate func setKeysArray(_ keys: LazyMapCollection<Dictionary<Date, [Person]>, String) -> [Date]{
var keysArray = [Date]()
for key in keys {
keysArray.append(key)
}
return keysArray
}
First, you'll need to clean timestamp before the sorting. You can do that by using Calendar and Date extension:
extension Date {
func noTime() -> Date! {
let components = Calendar.current.dateComponents([.day, .month, .year], from: self)
return Calendar.current.date(from: components)
}
}
Then you'll just need to sort your array by date without time:
let sortedByDate = persons.sorted { $0.inscriptionDate.noTime() < $1.inscriptionDate.noTime() }
Note. Be careful with compareDate function of Calendar, since it comparing only specific component. If in this example: NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, toUnitGranularity: .Day) you'll have same days in different months, the comparing result will show that dates are equal.
Assuming your inscriptionDate is a Date, why can't you sort on that? Since Date conforms to Comparable all you need is
let sortedByDate = persons.sorted { $0.inscriptionDate < $1.inscriptionDate }
I wright a code for you I thing this code useful for you.
//
// ViewController.swift
// sortData
//
// Created by Bijender singh on 26/01/18.
// Copyright © 2018 Bijender singh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
let myDataArray = NSMutableArray()
var myDataDic = NSMutableDictionary()
myDataDic.setValue("Bijender", forKey: "name")
myDataDic.setValue("1516965600", forKey: "date")
myDataArray.add(myDataDic)
myDataDic = NSMutableDictionary()
myDataDic.setValue("ben", forKey: "name")
myDataDic.setValue("1516965540", forKey: "date")
myDataArray.add(myDataDic)
myDataDic = NSMutableDictionary()
myDataDic.setValue("Deke", forKey: "name")
myDataDic.setValue("1516842180", forKey: "date")
myDataArray.add(myDataDic)
myDataDic = NSMutableDictionary()
myDataDic.setValue("Veer", forKey: "name")
myDataDic.setValue("1516842000", forKey: "date")
myDataArray.add(myDataDic)
myDataDic = NSMutableDictionary()
myDataDic.setValue("Ashfaq", forKey: "name")
myDataDic.setValue("1515981900", forKey: "date")
myDataArray.add(myDataDic)
print(myDataArray)
let sortedArray = self.sortDataWithDate(arrayData: myDataArray)
// sortedArray contane array which contan same date array
// you can use it according to you
// sortedArray.count is total diffrent dates in your array
// and (sortedArray.count[i] as! NSArray).count give you count of data of that date (0 < i < sortedArray.count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sortDataWithDate(arrayData : NSArray) -> NSArray {
// var chat: [ChatMessage]!
let returnArray = NSMutableArray()
var subArray = NSMutableArray()
let arrayDate = NSMutableArray()
for i in 0 ..< arrayData.count {
let msgDate = self.timeStampToDate(_timestamp: ((arrayData[i] as! NSDictionary).object(forKey: "date") as! String), _dateFormat: "dd/MM/yyyy")
print("dddt \(msgDate)")
// print("date array \(arrayDate) $$ msgDate \(msgDate)")
if arrayDate.contains(msgDate) {
subArray.add(arrayData[i])
}
else{
arrayDate.add(msgDate)
if arrayDate.count > 1 {
returnArray.add(subArray)
}
subArray = NSMutableArray()
subArray.add(arrayData[i])
}
}
if subArray != nil {
returnArray.add(subArray)
}
print(returnArray)
return returnArray
}
func timeStampToDate(_timestamp : String, _dateFormat : String) -> String{
// _dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
var date = Date(timeIntervalSince1970: TimeInterval(_timestamp)!)
date += TimeInterval(Int(TimeZone.current.secondsFromGMT()) as NSNumber)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = _dateFormat
let strDate = dateFormatter.string(from: date)
return strDate
}
}
In this code I insert array as hard coded
(
{
date = 1516965600;
name = Bijender;
},
{
date = 1516965540;
name = ben;
},
{
date = 1516842180;
name = Deke;
},
{
date = 1516842000;
name = Veer;
},
{
date = 1515981900;
name = Ashfaq;
}
)
And out put array is
(
(
{
date = 1516965600;
name = Bijender;
},
{
date = 1516965540;
name = ben;
}
),
(
{
date = 1516842180;
name = Deke;
},
{
date = 1516842000;
name = Veer;
}
),
(
{
date = 1515981900;
name = Ashfaq;
}
)
)
I am trying to get the objects from realm, where newDate is later then firstDate. So if the date from firstDate is 05.10.2017, it will get objects after that date, example 06.10.2017, but not 04.10.2017.
This is how I am storing the date:
class User: Object {
#objc dynamic var firstDate = Date()
#objc dynamic var newDate = Date()
}
This is how I am saving the objects:
let date = Date()
let realm = try! Realm()
let myUser = User()
myUser.firstDate = self.date
This is how I am trying to retrieve the objects:
var userData: Results<User>?
if (homeIndexPathRow == 0) {
let getData = realm.objects(User.self).filter("firstDate > newDate")
userData = getData
print("userData", userData!)
}
When trying to retrieve the objects, the app crashes.. Is it something wrong with the filter format?
Try this:
var yourNSDate = NSDate()
let predicate = NSPredicate(format: "firstDate < %#", yourNSDate)
let dataResults = realm.objects(User.self).filter(predicate)
userData = dataResults
Replace that with the code below if (homeIndexPathRow == 0) { ...
I am trying to read data using HealthKit but keeping getting the same issue when I run this code:
func readAge() -> ( age:Int?)
{
var error:NSError?
var age:Int?
// 1. Request birthday and calculate age
if let birthDay = healthKitStore.dateOfBirthWithError(&error)
{
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = NSCalendar.currentCalendar().components(.YearCalendarUnit, fromDate: birthDay, toDate: today, options: NSCalendarOptions(0) )
age = differenceComponents.year
}
if error != nil {
print("Error reading Birthday: \(error)")
}
return (age)
}
It gives me the error: Value of type HKHealthStore has no type dateOfBirthWithError
I can't tell why this doesn't work, because I've seen pretty much the exact same code work elsewhere.
With Swift 2 you can do it in this way:
func readAge() -> ( age:Int?)
{
var error:NSError?
var age:Int?
do {
let birthDay = try healthKitStore.dateOfBirth()
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: birthDay, toDate: today, options: NSCalendarOptions(rawValue: 0))
age = differenceComponents.year
} catch let error as NSError {
print(error.localizedDescription)
}
return (age)
}
In Swift 2.0, methods that take error-out parameters are handled differently than in Swift 1.0 and Objective-C. The method name is just dateOfBirth and it throws an NSError, which you can handle with a try statement.
I am trying to save a Date into a textfield and have that save into CoreData. I have the textfield set up and am able to use the date picker just fine with the NSDateFormatter but I am having trouble with getting it to save into the textfield into CoreData.
extension NSDate{
var stringValue: String{
return self.toString()
}
func toString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var dateValue: NSDate?{
return self.toDate()
}
func toDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
add this befor your class or another swift file,
then change textFieldDDate.NSDate = ddate to:
textFieldDDate.text = ddate.stringValue
you can only use text(String!) with UITextField,also only NSDate in your newItem.ddate.
change newItem.ddate = textFieldDDate.text to
newItem.ddate = textFieldDDate.text.dateValue
I see var ddate = data.valueForKey("ddate"), I guess it is type of NSDate? maybe you need change it to String, it can't be just use as!(?) String,if I am right, you need use my code of extension NSDate{} to change it too.
I checked your codes, just find some lines maybe it is save data to coreData:
if segue.identifier == "update" {
var selectedItem: NSManagedObject = myDivelog[self.tableView.indexPathForSelectedRow()!.row] as! NSManagedObject
let ADLVC: AddDiveLogViewController = segue.destinationViewController as! AddDiveLogViewController
ADLVC.divenumber = selectedItem.valueForKey("divenumber") as! String
ADLVC.ddate = selectedItem.valueForKey("ddate") as! NSDate
ADLVC.divelocation = selectedItem.valueForKey("divelocation") as! String
ADLVC.existingItem = selectedItem
}
am I right? I get this link of an answer of how to save a Data to CoreData for you. because maybe something wrong in there.
here it is https://stackoverflow.com/a/26025022/5113355