Sphero Connecting: Should I call setupRobotConnection and handleRobotOnline in each UIViewController or only once per app?

StackOverflow https://stackoverflow.com/questions/16489993

Вопрос

I created an iOS app that has 3 Sphero enabled flows. I ended up rewriting setupRobotConnection and handleRobot online in each viewDidLoad then closing the connection in each prepareForSegue method. It works for the most part but the NavigationController's Back button can screw things up. I'm thinking this isn't the best way connect to a Sphero and maintain the connection.

For my app, each flow had slightly different handleRobotOnline needs Flow 1: No driving, needs dataStreaming and AsyncData Flow 2: Multiplayer classes for sending commands. Flow 3: Joystick Driving with 1 view that required dataStreaming and AsyncData

My question is: for a multi-view app, where is the best place to: 1) Subscribe to app Notifications? 2) Subscribe to robot online/offline notifications? 3) Check if the app has the correct type of connection to the robot (driveControl, sharedMultiplayer, dataStreaming)?

I can paste code if necessary

Это было полезно?

Решение

It is best to manage your connection to Sphero and open/close it in one place. I find it is easiest to do this in the AppDelegate or the RootViewController.

For AppDelegate:

  • Open connection on applicationDidBecomeActive and applicationWillEnterForeground
  • Close connection on applicationWillResignActive and applicationWillTerminate
  • Register for robot state notifications in application didFinishLaunchingWithOptions

If you want to manage the connection in your RootViewController, register for robot notifications on load as well as the same application state notifications mentioned above and do the same connection handling.

By connecting in your AppDelegate/RootViewController you can allow your other ViewControllers to not care about handling the connection. You can either have them assume a Sphero is connected if you have logic to notify the user in AppDelegate/RootViewController, or you can share the state.

As for the particular use cases you mentioned I would recommend the following: 1. Add the data streaming and response observer on viewDidLoad, you should also enable data streaming here. Remove the observers on viewDidUnload and disable data streaming. 2. Use the multiplayer classes here as you normally would. 3. Add the data streaming and response observer on viewDidLoad, you should also enable data streaming here. Remove the observers on viewDidUnload and disable data streaming. Send joystick roll commands normally.

If you would like information about the robot connection state changing you can register/unregister for the connection notifications in each views viewDidLoad/viewDidUnload calls.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top