Where It Begins: AppDelegate

Before we even setup the app in the Rakefile, our app comes with some sensible defaults. Most importantly, it automatically compiles all Ruby files in the app directory of our project. Remember that app_delegaterb we mentioned earlier? It so happens that code was compiled with the app. In fact, it was the only code compiled with our app, so it’s probably a good idea to see what it does.

 class​ AppDelegate
 def​ application(application, didFinishLaunchingWithOptions​:launchOptions​)
 true
 end
 end

Hmm, all that did was define an AppDelegate class with one method. There’s not even a superclass, so how does this do anything at all?

Well, there’s a comment in our Rakefile that tells us to run the rake config command to see all project settings. Let’s run that.

 $ ​​rake​​ ​​config
 background_modes : []
 build_dir : "./build"
 .. ..
»delegate_class : "AppDelegate"
 .. ..
 xcode_dir : "/Applications/Xcode.app/Contents/Developer"

There’s that AppDelegate class, and it’s assigned as the delegate_class. What’s that do? Well, RubyMotion actually looks for a class with the name we assign as delegate_class and uses that as the application delegate when launching our app. We could’ve called our class SuperAppDelegate and changed our Rakefile to have the same result:

 Motion::Project::App.setup ​do​ |app|
  app.name = ​'HelloMotion'
  app.delegate_class = ​"SuperAppDelegate"
 end

What exactly is the application delegate? When the user launches our app, the system does some setup work to make sure everything loads correctly. We need to give the system an object that can take over after that setup is done; we refer to that object as the application delegate. It gets callbacks for all sorts of application-level events, such as when the app starts, ends, goes to the background, gets a push notification, and does all that other good stuff.

In the code generated by motion create, AppDelegate implements only the method application:didFinishLaunchingWithOptions:. This method and notation look a little different from normal Ruby code because of the named argument didFinishLaunchingWithOptions: shoved in the middle. For more information about named arguments, check out Why Are There Colons in My Ruby?.

application:didFinishLaunchingWithOptions: is called when the system finishes setting up the app and is ready for us to do our own setup. For now, just assume it will always return true. Some apps may want to use the launchOptions argument to determine whether the app should be started, but most of the time you won’t need that.

But aside from returning true and allowing the app to launch, our AppDelegate doesn’t do anything. Let’s change that by showing a quick UIAlertView.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset