MaeseppTarvo MaeseppTarvo - 1 year ago 77
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

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

and I have textField. Now I want that
input to be in array and if notification category button is pressed it deletes the first array item from the
. 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() {

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 {
} else {
newContact.phoneNumbers = [phoneNo]

var message: String = ""

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


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


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:, 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]()


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

let toFetch = [CNContactEmailAddressesKey]

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){}

guard let contact = contacts.first else{


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

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download