How to make only one piece of data affected by UserDefaults? - ios

So I just did a bit of research on UserDefaults last night and this morning and I wanna know how I can use dictionaries in a certain way. My issue is that when a user presses a certain button and the UserDefaults dictionary data gets set, every piece of data in the app is affected as well. My goal is to just have that piece of data affected only and the rest stay the same as they were before.
let eventDict = ["eventName": "\(selectedEventName!)", "purchased": true] as [String : Any]
This is the dictionary I set, pretty simple. And when the button is pressed I run this line of code.
self.defaults.set(eventDict, forKey: "eventDict")
These work perfect and I check the .plist file and everything is correct, it shows the event name and the purchased as 1 (true).
Now I tried to add some logic, in my viewDidLoad() of the page I purchase the event on and it works but when I check every other event the page has the same outcome, which is not what I want.
let checkEventStatus = defaults.dictionary(forKey: "eventDict")
if checkEventStatus?.isEmpty == false {
viewPurchaseButton.isHidden = false
cancelPurchaseButton.isHidden = false
purchaseTicketButton.isHidden = true
creditCard.isHidden = true
} else {
viewPurchaseButton.isHidden = true
cancelPurchaseButton.isHidden = true
}
I couldn't figure out how to retrieve an exact value from a key in a dictionary, so I just used isEmpty() instead which I thought would make sense because if the event wasn't purchased, it wouldn't have a dictionary with it's name in it.
These are the buttons I want to show up when the purchase button is pressed. The purchase button is hidden right now because it was already pressed, so the UserDefault data is set, and that effects the button visibility. Now when I check every other event, the screen is the same. I just want each screen to be a certain way depending on if the event is purchased or not using UserDefaults.

I think you have a fundamental problem - you're not actually saving any purchase status liked to an event in the first place, so there's no way you'll be able to determine the status for an event and set the button status accordingly. You need a data structure that associates the event name with the event status.
I think you'll need more thought into your data and workflow, but as a trival example that might get you started, you could create a Event struct to hold both name and status. You could also build in the purchase date and cost...
struct Event {
name: String
purchased: Bool
purchaseDate: Date?
cost: Double?
}
and then you could carry on using a dictionary in the form of [String: Event] where the key is some sort of string for event ID, but it'd probably be easier for now to work with an array [Event]
You could then iterate through the array showing all the events (or filter to get specific ones) and then set the screen up accordingly, for example if event is an item from the array
eventNameField.text = event.name
if purchased, let date = event.purchaseDate, let cost = event.cost {
purchasedDateField.text = "\(date)" //would really be a dateFormatted date
costFiled.text = "\(cost)"
}
purchaseButton.isHidden = event.purchased
cancelButton.isHidden = !event.purchased

Related

Retreiving data with Core Data

I'm working on a project where I should save data locally with Core Data.
Here is my workflow :
To start, I ask the user to fill a form, let's say his firstname and lastname.
He clicks on the submit button, then data is saved on the device using Core Data
User is redirected to the "last filled form" view controller.
I have a bar button item that when clicked can show the latest filled form.
I should test if the array of filled forms is empty, then the button should be disabled.
Otherwise, the button should be enabled ...
I tried this piece of code, where I fetch data from the database and affected to an array but the button seams not working at all and it never gets disabled ...
class ViewController: UIViewController {
var userIdentity: UserIDentity = UserIDentity(context: PersistanceService.context)
var identityArray = [UserIDentity]()
override func viewDidLoad() {
super.viewDidLoad()
self.fetchIdentityHistoryArray()
}
func fetchIdentityHistoryArray(){
let fetchRequest: NSFetchRequest<UserIDentity> = UserIDentity.fetchRequest()
do {
let identityArray = try PersistanceService.context.fetch(fetchRequest)
if identityArray.isEmpty {
self.identityHistoryButton.isEnabled = false
}
else {
self.identityHistoryButton.isEnabled = true
}
}
catch {
print("Error fetching sworn statement history !")
}
}
}
So I have 2 questions :
What's wrong with my code ?
How can I manage that when the user clicks on the "back button" for the first form filled ever, the "history button" can refresh itself and turn from disabled to enabled button ?
Any help is much appreciated. Thank you
You are initialising a core data object directly in your code
var userIdentity: UserIDentity = UserIDentity(context: PersistanceService.context)
This new object will exist in Core Data and will be included everytime you execute the fetch request. You must understand that Core Data is not a database layer it is an object mapping layer so even if you haven't called save() yet the object exists in the Core Data context.
Either change the declaration to
var userIdentity: UserIDentity?
or remove it completely if it isn't used.

Observing the changes to Object Swift 4

I have Swift object with about 20 Properties. In the app, there is a screen to get the user input and create the above swift object from the user entered value. Right now, if the user clicks the back button, all the user entered data will lose. So I want to alert the user to save the details if he/she has made any changes. How do we identify if the user has made any changes to the properties. Is it possible to use KVO in this case as we have too many properties?
What you need is a data model to hold the information in that particular screen, and then compare it with the original data when leaving the screen.
For the sake of simplicity, let's assume your screen has 2 text fields. One holds a name and another the age of a person.
struct Person: Equatable {
var name: String
var age: Int
}
When you first open this screen, the model will have the default values. Create a copy of this model and whenever the user makes any changes to the values on the screen, update the copy.
class YourViewController: UIViewController {
// Populate these 2 values when creating your view controller
var person: Person!
var personCopy: Person!
.
.
.
// You need to add this target to your text fields
#objc func textFieldDidChange(_ textField: UITextField) {
switch textField {
case personTextField:
personCopy.name = personTextField.text!
case ageTextField:
personCopy.age = Int(ageTextField.text!)!
default:
// Handle other text fields here or write separate cases for them
}
func dismissView() {
if person == personCopy {
// Dismiss your view
} else {
// Show alert
}
}
}
If the user presses the back button, all you need to do is compare these 2 models and check if they are the same. If they are the same, you can go back, if not, prompt an alert asking the user to save changes or discard.
I think KVO would be overkill here. Use KVO only for distant objects in your app.
Here you have the UITextFields in your viewController and you must have reference to the user object anyway.
Easier is: On the back button press you would check all text properties of your UITextField objects to the (existing) values of your user object. If one of them has changed then present the alert.

Tableview reloads when delegate function is called from one View, not from another.

I'm working on a part of my app where a user can have different banks, and the user can redeem credits from the bank.
The problem I'm having involves three TableViewControllers:
BankTVC is a list of the user's banks.
AddBankTVC is a static Table View where the user fills out the bank info
BankDetailTVC is a view where you can look at the details of the bank, and redeem credits.
BankTVC gets the banks to list in viewDidLoad by calling a function in my model that returns all the banks. AddBankTVC is accessed by an Add button in the navigation bar. BankDetailTVC is accessed by tapping on the cell with the bank in it.
func loadBanks() -> [Bank] {
let bankFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Bank")
bankFetch.sortDescriptors = [NSSortDescriptor.init(key: "lastUpdated", ascending: false)]
let loadedBanks = try! context.fetch(bankFetch)
if loadedBanks.count == 0 {
let sampleBanks = addSampleBanks()
return sampleBanks
}
print("Loaded Banks")
return loadedBanks as! [Bank]
}
BankTVC conforms to the BankModifierDelegate protocol, which requires it to have a function called bankWasModified(). This just reloads the banks from the model
func bankWasModified() {
print("Bank was modified")
banks = bankModel.loadBanks()
tableView.reloadData()
}
When bankWasModified is called from AddBankTVC, BankTVC updates with the new information cell. However, when bankWasModified is called from BankDetailTVC, the information is not updated in BankTVC when I return to it. However, when I dismiss BankTVC and then go back into it, the information is updated.
I know that the context is being saved from my console output. The context is saved, bankWasModified is run, the banks are reloaded. Not sure what is going on.

Cycle through array in iOS

In this app I save an NSOrderedSet of cards to a "Subject" entity in core data so that users can quiz themselves. The card flips and drags in tinder like fashion well but in the update card method I'm having some trouble. The current card displays fine as I set that in view did load (the first card of the NSOrderedSet's array property). When I drag and update however it immediately goes to the last card, for example if I have 5 cards in a deck it will start with the first then immediately go to the fifth. What would be the best way to update this method so that it will cycle through as desired?
I suppose I should pass it an index property like a tableViewDelegate method but if someone has done something like this before and has a better way that's greatly appreciated.
Thanks for the help like always.
func updateCard() {
//cycle through questions here
for var i = 0; i < (self.subject.cards?.count)!; i++ {
self.currentCard = self.subject.cards?.array[i] as? Card
self.draggableView.questionLabel.text = self.currentCard?.question
self.draggableView.answerLabel.text = self.currentCard?.answer
}
}
Currently, when you call updateCard the for loop is computing at computer-speed and you only get to see the last index.
Here's one option:
In your class, set a stored variable called selectedCardIndex as an implementation detail and then just increment and update the view in updateCard.
var selectedCardIndex = 0
func updateCard() {
self.selectedCardIndex += 1
self.currentCard = self.subject.cards?.array[self.selectedCardIndex] as? Card
self.draggableView.questionLabel.text = self.currentCard?.question
self.draggableView.answerLabel.text = self.currentCard?.answer
}

Dynamic updating of label/button title in Swift

I want to update the title property of a user interface element on iOS using Swift. In this case it is a UIBarButton, but it could be a UILabel, UIButton or whatever. Currently I am using this code, which works:
func setStatusMessage(barButton: UIBarButtonItem) {
let currentVersion = StatusModel.getCurrentVersion()
var statusUpdates = [StatusModel]()
var statusForCurrentVersion: StatusModel!
var statusMessage = String()
// check if update required before setting the text
checkIfLocalStatusNeedsUpdate()
barButton.title = getLocalStatusMessage()
// Try to update status anyway...
getStatusFromRemoteSource { (statusUpdates) -> Void in
for status in statusUpdates {
if status.version == currentVersion {
statusForCurrentVersion = status
}
}
self.saveStatusFromRemoteSource(statusForCurrentVersion)
barButton.title = statusForCurrentVersion.message
}
}
Although effective, this solution is ugly too as it does require a user interface (view) element to be embedded in my model. Not exactly a sort of MVC beauty.....
I cannot simply use return because the local status will be returned before the remote status can be fetched. So I guess I need some kind of handler / listener / delegate (/*getting lost here*/) to update the view dynamically. In this case that means: set the title using the locally stored value and update it if a remote value is received.
What is the best way to approach this scenario in a MVC compliant way, removing UI elements from the model code (thereby increasing reusability)?
One intermediate step you could do is going over the controller to the UI, by replacing the barButton parameter with a reference to the controller
barButton.title = statusForCurrentVersion.message
->
self.controller.update(title: statusForCurrentVersion.message)
This way your code is allowed to grow (updating more labels etc), but it comes with a cost of more code and harder readability.

Resources