How to set/unset multiple accounts for API credentials

I have an app that saves multiple user accounts for retrieving data from my API. There is always one account set to be active or flagged TRUE. When I select a different account I deactivate previously active account and activate selected account or set it to be TRUE. I do these using CoreData in my Accounts table view.

When my app starts my API class checks my CoreData to see which account is active and assigns its credentials to my Credential object.
I then use these credentials to access and get data from my server. All works perfect until this point.

My problem is when I select a different account and reset my Credentials object in my didSelectRowAtIndexPath method, my API class still has the previously active account’s credentials. I can see/print the Credentials object has the selected account’s credentials.

How do I adjust my objects to have/use only selected account’s credentials?

class API {
    var credentials:Credentials!
    init(){
        self.credentials = getActiveStore()
        // I use self.credentials.username to make API calls later in the code
    }


 func getActiveStore() -> Credentials?{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    let fetchRequest = NSFetchRequest(entityName: "User")
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format: "active = %@", 1 as NSNumber) 
    var error:NSError?

    let fetchResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [User]
    if fetchResults.count == 1 {
        let name = fetchResults[0].name
        let url = fetchResults[0].url
        let username = fetchResults[0].username
        let password = fetchResults[0].password
        return Credentials(name: name, url: url, username: username, password: password)
    }
    return nil
}

}

Now this is the class that never changes. When I refresh my data after selecting a different account, the data I see belongs to previously active account. API class doesn’t want to change.


Source: oop

Leave a Reply