MaeseppTarvo MaeseppTarvo - 6 months ago 26
Swift Question

Best way to handle temporary value in swift using coredata

I am trying figure out what would be the best option to save some info into cache. I want it to be in there until notification pops out and button is pressed. I am already done everything else but I do not know what is the best solution for handling temporary values in cache. I need to use them even if app is closed. Is

CoreData
the best solution with
NSUserDefaults
? Lets assume that I have an array:
var myArray = []

and I have textField. Now I want that
texField
input to be in array and if notification category button is pressed it deletes the first array item from the
myArray
. I need all this even if app is closed. Faulty code is inside "**".

Edit: The main problem is that how can delete every time the last value from array? It is not working if app is closed but works if it is opened.

This is what i've done so far.
This is whre I call out notification and it's action:

//**viewDidLoad function**\\
override func viewDidLoad() {
super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self, selector: "actionOne:", name: ACTIONONE, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "actionTwo:", name: ACTIONTWO, object: nil)

}


This is my array:
var myArray = [String]()


Here I add object into array:

@IBAction func addContact(sender: AnyObject) {

var newContact = CNMutableContact()

if isUpdate == true {
newContact = updateContact.mutableCopy() as! CNMutableContact
}

//Set Name
newContact.givenName = nameField.text!

//Set Phone No
let phoneNo = CNLabeledValue(label:CNLabelPhoneNumberMobile, value:CNPhoneNumber(stringValue:phoneField.text!))

if isUpdate == true {
newContact.phoneNumbers.append(phoneNo)
} else {
newContact.phoneNumbers = [phoneNo]
}

var message: String = ""

do {
let saveRequest = CNSaveRequest()
if isUpdate == true {
saveRequest.updateContact(newContact)
message = "Contact Updated Successfully"
} else {
saveRequest.addContact(newContact, toContainerWithIdentifier: nil)

**myArray.append(nameField.text!)

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(myArray, forKey: "object")

print(myArray)**

message = "Added Successfully"
}

let contactStore = CNContactStore()
try contactStore.executeSaveRequest(saveRequest)

displayAlertMessage(message, isAction: true)
}
catch {
if isUpdate == true {
message = "Unable to Update the Contact."
} else {
message = "Unable to Add the New Contact."
}

displayAlertMessage(message, isAction: false)
}
let userInfo = ["url" : "Hello"]

LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("TempCo", title: "Open app", message: "Your contact needs to be deleted!", date: deadlinePicker.date, userInfo: userInfo)
}


And now if notification is fired and button is pressed I would like to fire this function to delete first object from array:

func contactDelete(notification : NSNotification){

**let defaults = NSUserDefaults.standardUserDefaults()
let array = defaults.objectForKey("name") as? [String] ?? [String]()

myArray.removeAtIndex(0)**

let predicate = CNContact.predicateForContactsMatchingName(nameField.text!)

let toFetch = [CNContactEmailAddressesKey]

do{
let contacts = try contactStore.unifiedContactsMatchingPredicate(predicate,keysToFetch: toFetch)
guard contacts.count > 0 else{
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
return
}

guard let contact = contacts.first else{

return
}

let req = CNSaveRequest()
let mutableContact = contact.mutableCopy() as! CNMutableContact
req.deleteContact(mutableContact)

do{
try contactStore.executeSaveRequest(req)
print("Success, You deleted the user")
} catch let e{
print("Error = \(e)")
}
} catch let err{
print(err)
}
print("tere")
}

Answer

You can use NSUserDefaults. They are accessable if the app is closed or open. Read more about NSUserDefaults Here

Saving Example:

 NSUserDefaults.standardUserDefaults().setObject(nameField.text!, forKey: "name")

Retrieving Example

Best Practice

if let predicate = NSUserDefaults.standardUserDefaults().objectForKey("name") {
//NSUserDefaults has a value
} else {
 //NSUserDefaults does not has a value
}
Comments