martijnwalraven / meteor-ios

Meteor iOS integrates native iOS apps with the Meteor platform (http://www.meteor.com) through DDP
MIT License
740 stars 79 forks source link

App connected to DDP server after application:didFinishLaunchingWithOptions return #83

Closed khoanguyen-3fc closed 8 years ago

khoanguyen-3fc commented 8 years ago

I'd encounter a problem when show user data on initial view load (user logged in), as I see the problem is user data fetch before app connected to DDP server.

My question is how to ensure app connected to DDP server before AppDelegate application:didFinishLaunchingWithOptions return?

Here is my code:

   var currentUser: User? {
      if let userID = Meteor.userID {
         let userObjectID = Meteor.objectIDForDocumentKey(METDocumentKey(collectionName: "users", documentID: userID))
         return (try? managedObjectContext.existingObjectWithID(userObjectID)) as? User
      }
      return nil;
   }

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        self.managedObjectContext = Meteor.mainQueueManagedObjectContext

        print(Meteor.userID!)

        if let currentUser = self.currentUser {
            emails = currentUser.emails?.map { email -> String in
                return email["address"] as! String
                } ?? []
            numbers = currentUser.phones?.map { phone -> String in
                return phone["number"] as! String
                } ?? []
        }
    }

AppDelegate:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        Meteor.connect()

        if (Meteor.userID == nil) {
            // user not logged in, move to login view
            let storyboard = UIStoryboard(name: "Start", bundle: nil)
            self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("StartController") as! UINavigationController;
        }

        return true
    }

Output of console:

2016-02-01 16:41:21.686 MyProject[2736:1111626] Connecting to DDP server at URL: ws://xxx.yyy.net/websocket
view did load
NTp5bxsR9eRgchorz
2016-02-01 16:41:23.320 MyProject[2736:1111591] Connected to DDP server with protocol version: 1, sessionID: ADAdaRREHBF9BTNDZ
seviu commented 8 years ago

By listening to METDDPClientDidChangeConnectionStatusNotification and setting everything up there:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "connectionChanged", name: METDDPClientDidChangeConnectionStatusNotification, object: getMeteor())

func connectionChanged() { if getMeteor().connected { ... } }