Created
February 3, 2016 05:53
-
-
Save saintc0d3r/c75a21071eefb7e9b503 to your computer and use it in GitHub Desktop.
A demo of Core Data's Fetch, Insert , Update
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func keep_user_info_into_local_storage(json: JSON){ | |
// If success, store the returned credential into Core.Data | |
// 1. Try to retrieve existing record | |
let managed_object_context = app_delegate.managed_object_context | |
// 2. Fetch AuthenticatedUser record | |
let fetch_request = NSFetchRequest(entityName: "AuthenticatedUser") | |
// 3. Execute fetch request | |
do{ | |
let results = try managed_object_context.executeFetchRequest(fetch_request) | |
var authenticated_users = results as! [NSManagedObject] | |
var authenticated_user :NSManagedObject? | |
if (authenticated_users.count > 0){ | |
// Update existing | |
authenticated_user = authenticated_users[authenticated_users.count - 1] | |
} | |
else { | |
// Create & add a new one | |
let entity_description = | |
NSEntityDescription.entityForName("AuthenticatedUser", inManagedObjectContext: managed_object_context) | |
authenticated_user = | |
NSManagedObject(entity: entity_description!, insertIntoManagedObjectContext: managed_object_context) | |
} | |
authenticated_user!.setValue(true, forKeyPath: "is_authenticated") | |
authenticated_user!.setValue(json["userId"].stringValue, forKeyPath: "user_id") | |
authenticated_user!.setValue(json["id"].stringValue, forKeyPath: "token") | |
authenticated_user!.setValue(json["ttl"].stringValue, forKeyPath: "ttl") | |
if let fullname :String? = json["first_name"].stringValue + json["last_name"].stringValue { | |
authenticated_user!.setValue(fullname, forKeyPath: "full_name") | |
} | |
// TODO: Load addiitonal authenticated user's info (profile picture, first_name, last_name)from somewhere | |
// authenticated_user!.setValue(json["email"].stringValue, forKeyPath: "email") | |
// authenticated_user!.setValue(json["username"].stringValue, forKeyPath: "user_name") | |
// authenticated_user!.setValue(json["first_name"].stringValue, forKeyPath: "first_name") | |
app_delegate.save_context(nil) | |
} | |
catch let error as NSError { | |
print("Could not fetch record: \(error)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment