Finding the username in an AIR app, and a quick binding tip

Gary asked me an interesting question relating to AIR applications. He wanted to know if there was a way for an AIR application to know the username of the current user. I would have guessed that this would be part of the AIR API, but after a bit of searching and asking around, it turns out that this is not the case.

While there isn’t a direct API, there is a nice workaround that I found on Stack Overflow (Get the current logged in OS user in Adobe Air). The solution simply assumes that all users have a base directory that includes their username. On my Mac, it is “/Users/ray”. On my Windows box (yes, I’m ashamed, I still keep one around), the directory is “c:\documents and settings\administrator”. So this technique seems like a good one. You could certainly use it to suggest the current username. Here is a simple demo that Gary cooked up using this technique:

<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" horizontalAlign="center" verticalAlign="middle">

<mx:Script> <![CDATA[

public function currentOSUser():String { var userDir:String = File.userDirectory.nativePath; var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1); return userName; }

]]> </mx:Script>

<mx:Text text=”{currentOSUser()}” fontSize=”75” horizontalCenter=”true”/> <mx:Text text=”is a winner!” fontSize=”20” />

</mx:WindowedApplication> </code>

I modified it a bit just to simplify things. Running it on my Mac I see:

On my PC (oh, and I loved how the AIR installer noticed my PC was a bit behind on the AIR SDK and updated itself) it displayed:

Ok, one last tip. Gary was trying to use binding with this method and had trouble getting it working. Let’s look at what he did.

public function currentOSUser():String { var userDir:String = File.userDirectory.nativePath; var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1); return userName; }

protected function list_creationCompleteHandler(event:FlexEvent):void { getMyUnitResult.token = Widget.getMyUnit(“{currentOSUser()}”); } </code>

This didn’t work for him. Notice the binding inside the function? That’s simply not a place where you can use binding. In this case the solution was simpler code:

getMyUnitResult.token = Widget.gyMyUnit(currentOSUser())

My understanding is that you can only use bindings in the attributes of components. However, don’t take my word for it. I found a nice article at Adobe specifically on binding: Using data binding

Hope this helps!

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments