David Davis Jr. David Davis Jr. - 1 year ago 88
iOS Question

Passing data from completion block to view controller swift 3

!I have been stuck for 2 days on this issue. Here is my scenario.

User clicks login button, if email address and password are stored in

, the app silently login the user in, first presenting an
while retrieving the user's data from the server. Once the data is returned to the app, a completion handler assigns a local property
var User: [String: AnyObject]
the results. I can
at this point and the data is properly assigned. All good. The problem occur when I try to pass this data to the next controller that I am presenting via
. Here is my code:



dismiss(animated:true, completion: {
let tenantViewController = storyboard.instantiateViewController(withIdentifier :"tenantDashboardViewController") as! TenantDashboardViewController
tenantViewController.User = user
print(tenantViewController.User) //Works
self.present(tenantViewController, animated: true)

Here is my destination viewcontroller

import Foundation
import SideMenuController

class TenantDashboardViewController: SideMenuController {

var User: [String: AnyObject]?

override func viewDidLoad() {

performSegue(withIdentifier: "showTenantDashboardHomeViewController", sender: nil)
performSegue(withIdentifier: "containTenantSideMenu", sender: nil)

print(self.User!) //Always returns nil, crashes app


Thanks in advance!

Answer Source

If you're storing a user object app-side, you should store the User Object in NSUserDefaults. Make it NSCoding compliant so you can encode/decode the User class as you need to.

Then, as Matthew states, store your username/password combo in Keychain, because it is extremely sensitive and Keychain is designed to protect your users' credentials in a secure way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download