MAY 2012
using the swiz framework and data/services for mobile apps with flash builder 4.5
- BY: JACK FREUDENHEIM
- POSTED: MAY 6, 2011
httpv://www.youtube.com/watch?v=6yCAIwdrOUA
Introduction
In this tutorial, I’m going to share the process I’ve followed for creating mobile apps using Flash Builder 4.5 with the popular micro-framework Swiz 1.0. I won’t get into what Swiz (http://swizframework.org/) and its competing micro-architectures are; there are volumes of blogs and articles about that elsewhere; let’s assume you have a sense of what Swiz is, what inversion of control and dependency injection are, and want a quick start tutorial on using Swiz in your mobile app, similar to the web-app oriented one on the Swiz site.
Also, in order to make this a more useful sample, we’ll take advantage of the Data/Services features that debuted in Flash Builder 4. Many people who upgraded from Flex 3 to Flash Builder 4 didn’t notice or hadn’t the time to investigate some of the new features in FB4, and may have lost out on the great time-saving tools to be found in that part of the product. Together, Swiz and Data/Services will help you get great mobile apps off the ground in no time.
If you’d like to cut to the chase and get the source to run and look at on your own computer, you can get it here.
The Task At Hand
We’ll create a simple application that will let us put Swiz and Data/Services through their paces. We want to query a service that delivers a list of CDs. When we tap on one of the CDs, we’ll see some details about it and we’ll also be able to tap a button that takes us to the iTunes store page for that CD. In real life, you would use an application server to feed you the list of CDs, but to keep this tutorial simple and server-agnostic, we’ll use an xml file located on my web site’s server: www.sounder.com/swiz/cds.xml. Feel free to improve on the code using your own web service, Cold Fusion server, php or anything else instead.
What you need
Download the Swiz project from the framework’s site: http://swizframework.org/ It’s well worth exploring the site for information and latest news about the project as well. Join the mailing list to keep up with the project on an ongoing basis as well. From the downloaded zip file, get the swiz-framework-v1.1.0-mobile.swc file (the version number may change when you download it, just make sure it ends with ‘mobile’); that’s what we’ll need.
Create the Project
Start a new project. We’ll call it SwizMobile.
The template type should be View-based application:
Since we’re using XML, choose none/other as the application server type:
You can add the Swiz library in the next dialog, or just copy the swc file it to the libs folder after the wizard is finished:
Set Up the CD Service
Using the Data/Services tab, we will let Flash Builder create a service to fetch the CD list. In the process, Flash Builder will also create a value object class for the CDs, so that when we call the service the list of CDs will automatically be created in that class type.
- Click the Data/Services tab, then click on the “Connect to Date/Service” tab, which brings you to this dialog box:

Fill in the URL to the xml file, press invoke, and fill out the dialog as illustrated here:
When you press Finish, you’ll see that several new files have been created for you in your projects folder structure, in a new services.cdservice package and a valueObjects package. The classes starting with the underscore character are for internal use; we’ll just need the CdService and Cd classes in our code.
Create a Controller Folder and Class
The last step we’ll take before getting down to our Swiz work, will be to create a controllers package (folder) and a class for our controller, CdController.as. In our simple example, we’ll follow the pattern of using a “view controller”, a class which holds the model needed for a view (in this case the list of CDs), and which mediates events broadcast by the view, calling services or whatever else is needed.
For now, just create the class and leave it in its default state:
Create a Custom Event
We’ll use a couple custom events as well. For now, create one more folder/package called events and create this simple event class, CdEvent:
[sourcecode language="actionscript3" wraplines="true"]
package events
{
import flash.events.Event;
public class CdEvent extends Event
{
public static const GET_ALL_CDS:String = ‘get_all_cds’;
public function CdEvent(type:String)
{
super(type, true, false);
}
}
}
[/sourcecode]
Swiz: Create the Beans
Our first step in using Swiz in our project will be to create a BeanProvider class that holds our beans. Beans are simply objects that we instruct Swiz to instantiate for us at startup and manage during the life of the application. Swiz will inject a bean into any class we want simply by using some metadata magic, as you’ll see below. Create a package/folder called configuration, and create our bean provider as an mxml class called Beans.mxml, like so:
[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<swiz:BeanProvider xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:swiz="org.swizframework.core.*"
xmlns:swizServices="org.swizframework.utils.services.*"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:util="util.*"
xmlns:controllers="controllers.*" xmlns:cdservice="services.cdservice.*" >
<fx:Declarations>
<swizServices:ServiceHelper id="serviceHelper"/>
<controllers:CdController id="cdController"/>
<cdservice:CdService id="cdService"/>
</fx:Declarations>
</swiz:BeanProvider>
[/sourcecode]
As you can see, we’ve created three beans, one of which is of our recently-created CdController class, another is of the CdService class that was generated by the Data/Services dialog, and the third is Swiz’s ServiceHelper class, which we’ll be using inside the CD controller to make a CdService call.
Initialize Swiz
In the main application file, SwizMobile.mxml, we’re going to stir the pot to make our magic beans. We’ll create a preinitialize event handler that creates our Bean Provider, creates a Swiz object and configures it, as below:
Broadcast the Event to Fetch the List of CDs
Now that everything is set up, we’ll signal the CD controller to fetch the CD titles by sending a message from the main app’s creation complete handler: In the header, add this:
[sourcecode language="actionscript3" wraplines="true"]
applicationComplete="init()"
[/sourcecode]
and then add the init() method like this:
[sourcecode language="actionscript3" wraplines="true"]
public function init():void{
var evt:CdEvent = new CdEvent(CdEvent.GET_ALL_CDS);
this.dispatchEvent(evt);
}
[/sourcecode]
Our main SwizMobile.mxml file now looks like this:
[sourcecode language="xml" wraplines="true"]
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:swiz="org.swizframework.core.*"
xmlns:configuration="configuration.*"
preinitialize="preInit(event)"
firstView="views.SwizMobileHomeView"
applicationComplete="init()"
>
<fx:Declarations>
</fx:Declarations>
<fx:Script>
<![CDATA[
import configuration.Beans;
import events.CdEvent;
import mx.events.FlexEvent;
import org.swizframework.core.BeanFactory;
import org.swizframework.core.BeanProvider;
import org.swizframework.core.SwizConfig;
import org.swizframework.core.mxml.Swiz;
public function preInit(event:Event):void
{
var swiz:Swiz;
var provider:BeanProvider = new Beans();
var beans:Beans = provider as Beans;
var config:SwizConfig = new SwizConfig();
config.setUpEventType = FlexEvent.PREINITIALIZE;
config.eventPackages = [ "events.*","controllers.*"];
swiz = new Swiz(this, config, new BeanFactory(), [ provider ]);
swiz.init();
}
public function init():void{
var evt:CdEvent = new CdEvent(CdEvent.GET_ALL_CDS);
this.dispatchEvent(evt);
}
]]>
</fx:Script>
</s:ViewNavigatorApplication>
[/sourcecode]
Now let’s jump back to our CD Controller class, and write a method to mediate the event we just broadcast:
[sourcecode language="actionscript3" wraplines="true"]
package controllers
{
import flash.events.IEventDispatcher;
import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import org.swizframework.utils.services.ServiceHelper;
import services.cdservice.CdService;
import spark.components.ViewNavigator;
import valueObjects.Cd;
public class CdController
{
[Inject]
public var serviceHelper:ServiceHelper;
[Inject]
public var cdService:CdService;
[Bindable]
public var cds:ArrayCollection;
[Mediate(event="CdEvent.GET_ALL_CDS")]
public function getAllCds() : void
{
this.serviceHelper.executeServiceCall(cdService.getData(),
getAllCdsResultHandler, faultHandler);
}
private function getAllCdsResultHandler(event:ResultEvent):void{
this.cds = event.result as ArrayCollection;
}
private function faultHandler(event:FaultEvent):void{
trace(event.message);
}
}
}
[/sourcecode]
Here’s where we start using Swiz-specific features by way of metadata tags:
[Inject] – the variable that follows this tag will have the bean from the bean provider injected into it, such that the serviceHelper variable will automatically be referencing the object created during pre-initialization.
[Mediate(event=”CdEvent.GET_ALL_CDS”)] – this tag tells Swiz to listen for a event of type CdEvent.GET_ALL_CDS as it is broadcast from anywhere in the application, and handle it with the method that immediately follows. In our case, we use the serviceHelper to call our CdService’s getData() method, as specified in the first argument to the executeServiceCall method. The second argument is the method to handle the result, and the third optional argument is a fault handler.
It is important to note that all variables and functions named in this way must be public, or Swiz will not find them.
So: our result handler takes the event result and casts it as an ArrayCollection. You’ll find when you run this, that ArrayCollection is indeed a collection of Cd value objects.
View the Results
If you run the app we’ve written so far with breakpoints set in the controller, you’ll see that we’ve now got a list of CDs on our hands, but we now have to display it. We’ve done all the heavy lifting already; what comes next is simplicity itself.
Open the main view: SwizMobileHomeView.mxml. You can change the title to read “CD Assortment”. Now open up a script block and type in the following:
[sourcecode language="actionscript3" wraplines="true"]
import events.CdChooseEvent;
import mx.collections.ArrayCollection;
import valueObjects.Cd;
[Bindable]
[Inject( source="cdController.cds", bind="true" )]
public var cds:ArrayCollection;
protected function cdList_clickHandler(event:MouseEvent):void
{
var cdChooseEvent:CdChooseEvent = new CdChooseEvent(CdChooseEvent.CD_ITEM_CHOSEN);
cdChooseEvent.cdVO = this.cdList.selectedItem as Cd;
cdChooseEvent.navigator = this.navigator;
dispatchEvent(cdChooseEvent);
}
[/sourcecode]
We’re using the [Inject] tag again, with a twist: rather than inject the entire controller object into the view, we’re just taking the cds Arraycollection member from the controller, and making it bindable.
Now all we have to do is use the CD collection to render in a list component in our view, using the built-in IconItemRenderer class:
[sourcecode language="xml" wraplines="true"]
<s:VGroup left="0" right="0" top="0" bottom="0">
<s:List id="cdList"
width="100%" height="100%"
dataProvider="{cds}"
click="cdList_clickHandler(event)"
>
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer
iconField="cover"
iconHeight="100"
iconWidth="100"
messageField="artist"
labelField="title">
</s:IconItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:VGroup>[/sourcecode]
and we’re almost ready to run the app.
Create a Run Configuration and Go!
The last step before running the app is to create a run configuration Here you can tell the simulator what phone to simulate as well as give Flash Builder what it needs to deploy straight to your mobile device:
Go ahead and press the Run button. If all went well, you’ll see the app looking like this:
There you have it; you’re using Swiz to create beans, and broadcast and receive events.
Using Swiz to Handle User Interaction
Before we stop, let’s create another event and corresponding handler to set in motion what happens when you tap on a CD item in the app’s list.
First, we’ll need a new event class, which we’ll call CdChooseEvent. This event type will carry some data along with it: the CD value object corresponding to the item chosen from the list, and a handle to the viewNavigator owned by the view.
The class’s code looks like this:
Broadcast the CdChooseEvent
In the SwizMobileHomeView’s cdList, add a click handler like this:
[sourcecode language="actionscript3" wraplines="true"]
click="cdList_clickHandler(event)"
[/sourcecode]
Then make a click handler function like this:
[sourcecode language="actionscript3" wraplines="true"]
protected function cdList_clickHandler(event:MouseEvent):void
{
var cdChooseEvent:CdChooseEvent = new CdChooseEvent(CdChooseEvent.CD_ITEM_CHOSEN);
cdChooseEvent.cdVO = this.cdList.selectedItem as Cd;
cdChooseEvent.navigator = this.navigator;
dispatchEvent(cdChooseEvent);
}
[/sourcecode]
What we’re doing is creating a new CdChooseEvent, populating it with the value object from the list, and passing it the view’s ViewNavigator.
Mediate the CdChooseEvent
Back in our CdController, we just need to add a function to mediate the event, like this:
[sourcecode language="actionscript3" wraplines="true"]
package events
{
import flash.events.Event;
import spark.components.ViewNavigator;
import valueObjects.Cd;
public class CdChooseEvent extends Event
{
public static const CD_ITEM_CHOSEN:String = "cd_item_chosen";
public var cdVO:Cd;
public var navigator:ViewNavigator;
public function CdChooseEvent(type:String)
{
super(type, true, false);
}
}
}
[/sourcecode]
What’s new here is that the Mediate tag accepts a second argument, called properties, which will be a comma-delimited string of arguments. These are read out of the event’s data members, and will automatically be provided as arguments to the function that follows the tag.
The full CdController.as code now looks like this:
[sourcecode language="actionscript3" wraplines="false"]
package controllers
{
import flash.events.IEventDispatcher;
import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import org.swizframework.utils.services.ServiceHelper;
import services.cdservice.CdService;
import spark.components.ViewNavigator;
import valueObjects.Cd;
import views.CdDetailView;
public class CdController
{
[Inject]
public var serviceHelper:ServiceHelper;
[Inject]
public var cdService:CdService;
[Bindable]
public var cds:ArrayCollection;
[Mediate(event="CdEvent.GET_ALL_CDS")]
public function getAllCds() : void
{
this.serviceHelper.executeServiceCall(cdService.getData(),
getAllCdsResultHandler, faultHandler);
}
private function getAllCdsResultHandler(event:ResultEvent):void{
this.cds = event.result as ArrayCollection;
}
[Mediate(event="CdChooseEvent.CD_ITEM_CHOSEN",properties="cdVO,navigator")]
public function showCd(cdVO:Cd, navigator:ViewNavigator):void{
navigator.pushView(CdDetailView,cdVO);
}
private function faultHandler(event:FaultEvent):void{
trace(event.message);
}
}
}
[/sourcecode]
Now we need to create the CdDetailView, which will be an mxml class we’ll put in the views package.
[sourcecode language="xml" wraplines="true"]
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="{this.cdVO.artist}">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import flash.net.navigateToURL;
import valueObjects.Cd;
[Bindable]
protected var cdVO:Cd;
public override function set data(value:Object):void{
this.cdVO = value as Cd;
}
protected function buyButton_clickHandler(event:MouseEvent):void
{
var urlRequest:URLRequest = new URLRequest(this.cdVO.purchaseLink);
navigateToURL(urlRequest);
}
]]>
</fx:Script>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<s:VGroup width="100%" height="100%" gap="20" horizontalAlign="center"
paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10">
<s:Label fontSize="29" fontWeight="bold" text="{this.cdVO.title}"/>
<s:Image id="coverImage" width="100%" scaleMode="letterbox" source="{this.cdVO.cover}"/>
<s:Button label="Purchase this CD on iTunes" id="buyButton" width="100%"
click="buyButton_clickHandler(event)"/>
</s:VGroup>
</s:View>
[/sourcecode]
Two things are notable in this class. One is that we override the set data function. This allows us to strongly type the data property that is set when the View Navigator instantiates this view, in our case casting it to the Cd class.
The second thing is that when a user taps on the buyButton, we’re handing the event within the view, using the navigateToUrl() method to open a browser to the iTunes link that was stored in the original xml document. Of course this event handling should take place in the controller: I leave that to you to pursue as a final exercise!
Here’s how our detail view looks:
[Note:] One extremely important thing before you save a production build: the Flash Builder compiler strips out metadata for production, and that’s what Swiz runs on, so to keep your app working just as it did in your debug version, you need to add this directive to the compiler, like so:














Hi!
Very good tutorial, but where can I get the full video please?
Thank you,
Gergely Rossel.
I have just asked the author, Jack Freudenheim, to respond. Maybe he can put it up. Cheers,
Robi
Hi Gergely,
The video posted here is all that is in video form. The written tutorial follows.
Thanks for your interest!
Jack
Hi Jack!
Oh.. that’s a pitty.. nevermind, I’ll go through this. Swiz looks the perfect tool what I need since it has the AOP capability.
Thank you,
Gergely