Archive for the ‘Mobile’ Category

Quick Patch: iTunes 10 detection using 1.4

Wednesday, September 1st, 2010

Tonight, Apple pushed the availability of iTunes 10. iTunes 10 has some issues with our detection script in Titanium and we have posted a patch here. To apply the patch:

1. copy the file into the following directory: /Library/Application Support/Titanium/mobilesdk/osx/1.4.0/iphone and name it prereq.py. (In some cases, Titanium is installed in your personal directory under ~/Library/Application Support/Titanium/mobilesdk/osx/1.4.0/iphone/).

2. in the console, make sure the file is executable: chmod a+x prereq.py

Now, Titanium will correctly detect the appropriate iTunes version and you should be good to go. This fix is already applied to master in Github.

Dealing with multiple screens and multiple languages

Sunday, August 22nd, 2010

In the upcoming 1.5, we’re adding some additional functionality to help you improve dealing with the various screens (thank you Android and RIM) as well as handling applications for a variety of languages around the world. These are two big areas that have needed much improvement and we’ve made some big changes (that landed this weekend in Git) to start to make the easier for you.

Internationalization and Localization (i18N)

Up until to date, there wasn’t a built-in Internationalization and Localization framework per se in Titanium. We’ve had numerous different approach to handling this, mainly through meta frameworks on top of Titanium. However, for 1.5, we’ve brought this in as a first-class citizen in Titanium. We’ve also made is cross-platform out of the box to help you deal with the various types of devices and specifics around how each platform handles it differently.

We’re adopting a new directory (optional) in the project root, aptly titled i18n. Inside this directory, you’ll create one or more directories for each locale/language combination you’re localized for. For example, for English, you could create a directory titled “en”. Or, for US english, you might create one titled “en-us”.

Inside this directory, you’ll create an XML file titled “strings.xml”. Save it either as UTF-16 or UTF-8 and then create your strings like so:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="welcome">Hello</string>
  <string name="format_test">My name is %s</string>
</resources>

Now, you might want to provide this localization also in Spanish. Let’s create another directory, titled “es” and create the following file:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="welcome">¡Hola</string>
  <string name="format_test">Mi nombre es %s</string>
</resources>

Now, this will automatically create the appropriate platform-specific localization files/bundles/etc when your application is compiled.

You have a couple of options for handling these strings in your application code.

First, you can use the new built-in L function. This is a short-cut to the longer Titanium.Locale.getString method.

alert(L("welcome"));
alert(Ti.Locale.getString("welcome"));

You’ll also sometimes need to format your strings. We’ve provided some new helper functions to make it easier to do that as well. For example, you can perform formatting for example:

var message = String.format(L("format_test"),"Jeff");

String.format takes a string formatted using IEEE printf specification.

You can retrieve the current locale using Ti.Locale.currentLanguage property.

Dealing with multiple screen sizes and varying layouts

We’ve been working on various techniques for how to deal with the differences in platforms, screen sizes and densities. As Android continues to grow and as we expand to new devices, it’s becoming apparent we need to provide better capabilities in this area and we’re making the first step of several in this direction.

In our experience and looking at all the source code of applications that come through support, it’s apparent that more than 60% of your time and code is spent in layouts. Constructing the UI can be rather easy in Titanium but can become tedious as you’re trying to make it work seamlessly and natively across different screens. It’s also hard to reuse layouts and code as well as make it portable if you’re not careful and thoughtful from the beginning.

We’re introducing a new native framework built-in that we’re calling JS Stylesheets or JSS. They’re are syntactically the same as Cascading Stylesheets (CSS) for the most part, but we’re calling the JSS to not confuse or interfere with HTML5 CSS you might want to include in your application.

Titanium does special stuff now with the introduction of JSS. First, you’ll create a file with the name of your context and the jss file extension and place it in your Resources directory. The Titanium compiler knows how to compile this file into special code.

Let’s give you a simple demonstration on how you’d use it in app.js. First, let’s start out by creating the new JSS-powered app.js file that creates a window with a simple button.

var window = Ti.UI.createWindow();
var button = Ti.UI.createButton( { id : "b" } );
window.add(button);
window.open();

OK, much less code. Now, let’s create the layout/styling of the button by creating a file named app.jss:

#b 
{
   width:100;
   height: 40;
   title: "Hello"; 
}

Now, we’ve externalized the layout/styling from the actual business logic. We have some very specific ideas on how to take this to the next level, including some layout tools, however, we’re going to stop there for 1.5 and make this solid first.

So, you’ll be able to also do some advanced layouts by naming convention. Say, you have a high-density device you want to have the sizes or positioning different. In those cases, the business logic of the application is the same. No more “if than else” in your code. Let’s do it with compile time JSS files.

Create a file named app.android.high.jss.

#b 
{
   width:200;
   height: 45;
   title: "Hello"; 
}

In this case, we’re saying on an Android high-density device, you a different set of stylings for the button with the id “b”.

You can also use CSS keywords like @import to import other files to combine them and to make it easy for meta frameworks on top of Titanium.

@import "common.jss";

So, how about internationalization and JSS? That’s easy with locale-aware keywords like titleid:

#b 
{
   width:200;
   height: 45;
   titleid: "button_b"; 
}

Beyond 1.5, we’ll have a lot more capabilities beyond as this is just one of the many ways we’re going to make it easier and faster for you to use Titanium in your cross-platform applications.

We’d love your feedback and ideas, too.

Onward to 1.5 and Android awesomeness

Thursday, August 19th, 2010

Since 1.4, we’ve been hard at work on the next release of Titanium, 1.5, scheduled in September. In 1.5, Android is become the golden child and it’s getting a lot of love and attention and some really awesome new capabilities and fixes. I’ll outline some of the specific things that will land in 1.5 (some are already available in master or on our android_native_refactor branch).

For iOS, here’s generally what we’re working on:

- Full background job support for iOS4. You’ll be able to create one or more JS files that will run when your application goes to the background.

- Local Notification support. You’ll have full support for local notifications. For example, when you go in the background, you might want to schedule a notification to fire that some event occurred to alert the user.

- Improved Split View in iPad. The Apple split view implementation is plain broken. It’s just not designed like everything else in the SDK and we’ve ditched it in favor of using Matt Gemmell’s awesome MGSplitViewController. That solves like all the bugs and provides a bunch of new capabilities we were limited with in Apple’s implementation.

- Fixed numerous rotation issues. We’ve fixed numerous rotation issues with iPad. This has been a pain and very complicated but I think with 1.5 all the known issues are squashed.

- Table View improvements. We’ve fixed a number of performance improvements around cell/subcell redrawing that was unnecessary that is improving performance.

For Android, here’s what’s coming:

-Major memory, footprint and execution speed. We’ve greatly improved the memory footprint, startup speed and bundle size and general speed improvements.

- Native support for Intents and Activities. You can now call third-party activities/intents from Android as well as your Titanium apps can register fine-grain activities/intent filters and work like a first-class citizen in Android.

- Support for background services. Very similar to iOS above.

- Improved Native pickers. We’re now support much nicer, iPhone-like, native pickers. You can still use the existing (and ugly) Android pickers or use some cool new ones.

- Image Caching. We now have a native image cache like iOS that helps cache often used remote images.

- Mixed Density Images. We are improving support for using the various image densities within Titanium.

- Improved animations. We’ve fixed a number of animation issues and improved the functionality.

In general:

- Localization/Internationalization. We are adding the new i18N framework natively in the SDK. You’ll be able to fully localize your application in a generic since and then we’ll automatically create the platform-specific localization resources, etc.

- Bug fixes. Many, many reported bug fixes and overall improvements based on your feedback.

From a timing standpoint, we think we probably have at least 2 more weeks worth of development before code complete so this will put the release sometime in September.

You can always continue to follow our development on Github at http://github.com/appcelerator/titanium_mobile/commits.

Thanks for everyone’s continued support and excitement around the platform. It’s amazing to see all the cool applications that you’re creating (over 3,000+) and how fast new apps are launching on the Apple iTunes store or Android Marketplace (40+ per day). Code strong!

Understanding Execution Contexts

Thursday, August 19th, 2010

A couple of questions have surfaced from community members recently with regard to execution contexts in a Titanium Mobile application. I thought I would take a few minutes to explain execution contexts to folks for whom the concept is still a little foggy. First, let me explain what I mean when I say “execution context”.

A JavaScript application running in a web browser is single threaded and has a global variable scope for the entire application. A Titanium Mobile application is similar, except that a single application may have multiple JavaScript processes running at once, each with it’s own unique scope. We call these “execution contexts”.

Every Titanium Mobile application has at least one execution context, the one created by the app.js JavaScript program which bootstraps your entire application. New execution contexts are created when a window is created that points to an external JavaScript file, which would then bootstrap the new window. We refer to windows that have their own execution contexts as “heavyweight” windows (making those that do not “lightweight” windows, since a window need not point to an external JavaScript file). The syntax for creating a heavyweight window is below, and familiar to the majority of you I am sure:

var win = Titanium.UI.createWindow({
  title: 'New Window',
  url: 'win.js'
});

When this new window is opened, it will have it’s own context and scope, so any variables declared in other contexts will not be available. Say that my app.js file contains the following code:

var awesome = true; //this is visible in the current execution context
var win = Ti.UI.createWindow({
  title: 'New Window',
  url: 'win.js',
  backgroundColor:'#fff'
});
win.open();

And win.js contains the following code:

var label = Ti.UI.createLabel({
  text: (awesome) ? 'JavaScript is awesome!' : 'Yeah, well so\'s your old lady!'
});
Ti.UI.currentWindow.add(label);

This example would fail because the code in win.js is not executed in the same context as the code in app.js, so the variable awesome is out of scope.

Occasionally, it is necessary for one context to communicate with another. This is accomplished using the custom events facility that is built into the Titanium API. You can fire application-level events that will be received in all currently active execution contexts (app.js plus any open windows) via fireEvent. Custom events can have arbitrary data passed along with them, as shown in the example below:

Ti.App.fireEvent('myCustomEvent', {
  myCustomEventValue: 'someValue'
});

You can listen for these custom events in any context by using addEventListener at the application level as well. The example below listens for our custom event – you’ll notice that any properties of the object passed as the second argument to fireEvent are available on the event object the callback function takes as an argument:

Ti.App.addEventListener('myCustomEvent', function(event) {
  Ti.API.info('You sent me: '+event.myCustomEventValue);
});

Note that only ACTIVE execution contexts will receive a custom event when it is sent, so any windows that are not yet open will not receive the event.

While not every application requires multiple execution contexts, it is good to know when execution contexts are created and how they work. Hope that helps, and let us know if you have any questions.

Titanium For New Developers (Webinar Slides)

Tuesday, August 3rd, 2010

Hi everybody, and thanks to those of you who checked out our Titanium For New Developers webinar this morning. Just wanted to quickly share the slides from this morning’s presentation, and invite you to join us tomorrow morning when we talk about the new features available in our 1.4 release. Here you go…

iOS package for distribution with 1.4+

Tuesday, July 27th, 2010

There have been a few questions around how to package for distribution for iOS starting with Titanium SDK 1.4. Apple has changed the requirement on how you package and submit your application to iTunes connect. You can no longer use the web-based portal to upload your application.

I thought I’d explain the steps on how to package and distribute with some screenshot walk throughs.

In Titanium, you’ll do the normal package for distribution step, selecting your distribution profile.

NOTE: I have circled the “Select Distribution Location” since this is no longer required. In 1.4 SDK, we ignore this value. We didn’t want to rev Titanium Developer just to remove this field and to keep in backwards compatible. However, you will still need to enter a value for this field. In a future release of Developer, we’ll improve this.

After packaging, we’ll automatically start Xcode Organizer. Select the “Archived Applications” on the left menu and you should see your Application with a package date.

If you select the date, you will be able to enable the buttons at the bottom.

First step, you’ll want to validate your application. This will actually validate your application with Apple prior to submission and let them perform some pre-flight checks.

You’ll need to login to iTunes connect before you can validate. (The first time, you’re credentials will be empty. Subsequent times, if you check “Remember my…” if we remember).

After successful login, you’ll need to choose the appropriate application and profile. IMPORTANT STEP: If you don’t have an application setup in iTunes Connect (on the website), these subsequent steps SILENTLY FAIL.

NOTE: Organizer gives no visual clues to as what’s happening. The UI will lock-up while it runs network operations and when it fails, it simply does nothing and you have no idea. The biggest problem I’ve encountered is when someone doesn’t actually have an application setup (see above).

Choose your app and profile and you should see this alert result (after a few seconds to minute):

Since you’re building with Titanium, everyone should work. However, we’ve seen a few issues mainly related to the wrong size icon when validating. Apple has gotten more strict on icon sizes, etc.

To submit your application, click the “Submit Application to iTunes Connect..” button. BEWARE: when you do this, it will immediately upload your app and submit it for approval (assuming that your application details are setup).

At this point, your application should be submitted and in the queue for approval.

Introducing Titanium Mobile 1.4

Tuesday, July 27th, 2010

OK, so this release took way longer than we all anticipated. We tried our best working days and nights and weekends to make it faster, but sometimes this stuff just takes longer than you’d like. In our case, we ran into a lot of major issues with iOS4 and between the various devices, versions and permutations. There’s quite a bit of more work we intend to do starting tomorrow for 1.5 but we feel like this release is much improved over the 1.3.2 drop we did 2 weeks ago.

Thanks for everyone’s patience and assistance during this time. We fixed well over 200 reported bugs as well as worked through many many more we found in our own testing. There’s a lot of great improvements in this release and a few new things. The full release notes can be found on the documentation page for the release.

Next up is 1.5. We’ll be publishing more information about the next release once we’ve had some time to rest, review with the engineering, support and QA teams and write it all up.

We also have a bunch of new high quality documentation that will roll out soon, thanks to two of our newest members of our official Training team we added awhile back. We hope to have more information about that very soon. Stay tuned!

UPDATE (7/27 10:30PM ):

There’s a logging issue that Apple introduced with 4.0.1 that affects logging while running your app in the simulator.

You can get the hot patch for this by downloading this file (name it logger.py). Drop this into your /Library/Application Support/Titanium/mobilesdk/osx/1.4.0/iphone directory. Make sure that you chmod a+x the logger.py file to make it executable. No need to restart Titanium Developer. Just re-launch your app in the simulator.

Twitter oAuth Implementation for Titanium Mobile

Friday, July 9th, 2010

We have a great community project to highlight today – David Riccitelli (follow @ziodave on Twitter here) has developed a pure JavaScript oAuth helper library for Titanium Mobile (today it’s iPhone only, but if you check out source on Google Code I’m sure one of us can rectify that).

If you’d like to use it, your first step is to register your application at Twitter’s developer site. Once you do that, you should be able to grab your application’s consumer key and shared secret:

Once your app is set up, you’re ready to integrate David’s Twitter library. Create a new Titanium Mobile project, and under the Resources directory, create a /lib folder. In this directory, you will place the required JavaScript files for David’s library – all three files are linked from David’s guide:

Your next step is to integrate Twitter for fun and profit! In app.js, drop in the following code to see a simple example in action:

var oAuthAdapter = new OAuthAdapter(
        '<your-consumer-secret>',
        '<your-consumer-key>',
        'HMAC-SHA1');
 
 
// load the access token for the service (if previously saved)
oAuthAdapter.loadAccessToken('twitter');
 
oAuthAdapter.send('https://api.twitter.com/1/statuses/update.json', [
  ['status', 'hey @ziodave, I successfully tested the #oauth adapter with #twitter and @appcelerator #titanium!']
], 'Twitter', 'Published.', 'Not published.');
 
// if the client is not authorized, ask for authorization. 
// the previous tweet will be sent automatically after authorization
if (oAuthAdapter.isAuthorized() == false) {
    // this function will be called as soon as the application is authorized
    var receivePin = function() {
        // get the access token with the provided pin/oauth_verifier
        oAuthAdapter.getAccessToken('http://twitter.com/oauth/access_token');
        // save the access token
        oAuthAdapter.saveAccessToken('twitter');
};
 
    // show the authorization UI and call back the receive PIN function
    oAuthAdapter.showAuthorizeUI('http://twitter.com/oauth/authorize?oauth_token=' +
        oAuthAdapter.getRequestToken('http://twitter.com/oauth/request_token', [['oauth_callback', 'oob']]),
        receivePin, PinFinder.twitter);
}

You’ll find that once you have signed in once to Twitter, you will be able to successfully update your stream without re-authorizing, as David is storing your authorization token locally. Very cool stuff, thanks David! David also recently published this quick video demonstration of his Twitter library in action in his own (also cool) Titanium app, which is embedded below. Please show David some love for his very useful contribution!

Twitter OAuth in Titanium from David Riccitelli on Vimeo.

How-To: Perform CRUD operations on a local database

Thursday, July 1st, 2010

One of the most requested items from our Skribit widget was a step by step example of how to do database operations in Titanium. Well, ask and ye shall receive! If you haven’t noticed it already, you can suggest topics for us to include on this blog by using the Skribit widget on the left-hand side of the blog home page (black box marked “Suggestions”). Heeding the will of the people, I thought I would write up a quick example of how to do Create, Read, Update, and Delete (CRUD) operations against a local database in Titanium. This example was written for Titanium Mobile, but the code works with minimal modifications in Titanium Desktop as well.

In this example, we will implement our database operations using the Module pattern – here’s a good tutorial if you’re not familiar with this useful JavaScript design pattern. We will implement standard CRUD against a local database that we will create upon initialization. If you’d prefer to just look at the code (it is well commented to show what is going on), it’s embedded from this Gist at the end of the article – just drop it in app.js to see it log messages to the console in a Titanium Mobile application. For more explanation on using a local database with Titanium Mobile, read on.

Database Basics

Titanium Mobile gives you low level access to a SQLite database. Most of your interaction with a local database (docs) will be through raw SQL, which you run against your database with the execute function. SQLite is a full featured SQL database, although it does have more limited data types than you might be used to. For more information on SQLite, please refer to their reference documentation. If you are brand new to programming with SQL, W3 Schools has a nice tutorial which starts at the very beginning.

Creating a Local Database

You have two options for creating a local database. You can either create one inline using SQL (as in the example code below), or you can use a pre-populated SQLite database in your Resources directory by calling Ti.Database.install. If you use the “install” method, don’t worry – it is safe to call multiple times. After the first time the database is loaded, subsequent calls will use a persistent version of the database in your application’s data directory.

Working with a Database

As I mentioned earlier, interaction with a database through the Titanium.Database API is typically done through raw SQL statements. You will use CREATE, UPDATE, INSERT, and DELETE actions to modify the contents of your database. For every action you execute against the database, you will receive a Result Set. The result set object allows you to iterate over the result (or results) of your query, and pull data out of the query. If you do iterate over the results of a query, it is important to call “close” on the result set when you are finished, as in the example.

Example Code: TODO List

In the sample code below, we define a JavaScript module which performs operations on our database. When the module is created initially, it populates the database with the tables it needs if they do not exist. Note that the slash in the SQL string simply denotes a multi-line JavaScript string:

//maintain a database connection we can use
var conn = Titanium.Database.open('todos');
//Initialize the database
conn.execute('CREATE TABLE IF NOT EXISTS \ 
  todos (id INTEGER PRIMARY KEY, todo TEXT)');

In this case, we have just a single table with TODO items in it. We also maintain a reference to our application database which we can use in all of our API functions. Our public API has operations to read, update, create, and delete records in our database. When working with a ResultSet, you can get properties from the table row using fieldByName:

//Get TODOs from database
var resultSet = conn.execute('SELECT * FROM todos');
  while (resultSet.isValidRow()) {
    results.push({
      id: resultSet.fieldByName('id'),
      todo: resultSet.fieldByName('todo')
    });
    resultSet.next();
  }
resultSet.close();

This example shows how one might approach implementing database operations in a Titanium application. Typically, you would want to separate database logic into a JavaScript file that you could include in multiple windows, so that all your database interaction is contained in one place. The complete source code for this simple application is found below – to run it, simply copy the code into an app.js file in a brand new Titanium project. There is no UI for this application, so check the console in Titanium Developer for the results of the tests found at the bottom of the script. Hope that helps!

1.3.2 (1.4 RC1) Release Now Available

Monday, June 21st, 2010

As promised (but a little late), we’re going to make the upcoming 1.4 release candidate (1.3.2 release) available manually here. Please read for instructions and links to the files. For now, you’ll have to install manually until we can get some good feedback on the release and push the official 1.4. Our goal is to get feedback this week, do our final round of fixes and testing and release the final release early next week.

First, the links to the download links:

OSX (iPhone/Android): http://bit.ly/cyTWkA
Win32 (Android): http://bit.ly/90TmIY
Linux (Android): http://bit.ly/bSgTjo

To install, you’ll want to download the appropriate distribution above and then extract into your Titanium directory.

For example, on OSX, your Titanium directory will be under either /Library/Application Support/Titanium or ~/Library/Appcelerator Support/Titanium.

Once you locate your Titanium directory, extract the zip file into this directory. The zip file will expand the contents and create/overlay some new directories for 1.3.2.

NOTE for OSX users who use Safari to download: Safari by default will auto uncompress your downloads, how handy. However, if you have a directory named mobilesdk, your extracted directory will be renamed. On OSX, I suggest you use curl and do it the old fashion way. In the terminal, go to your Titanium directory and then run the following commands:


> curl -L http://bit.ly/cyTWkA >mobilesdk-1.3.2-osx.zip
> unzip -o mobilesdk-1.3.2-osx.zip

Now, you’ll need to restart Titanium Developer to pick up the new release. Once restarted, remember to change your application SDK version and then click the ‘Save’ button.

You should now be able to test with the latest release.

A few things to note:

- This release still has some issues we’re working through. You can see the latest fixes and outstanding items for 1.4.0 here. All the items on the list are not going to be fixed for the final 1.4.0 and will automatically roll into the next release (if not resolved).

- This release fixes all known crashes on iOS 4. There are a few issues we’re still working on but this release addresses the major issues we’ve found so far.

- This release is mainly a maintenance release and fixes hundreds of Android and iOS bugs. We have added some stuff that I’ll try and summarize below. We’ll have the full release notes and documentation up once 1.4 is final.

Some updated stuff worth noting:

- iAds is here! By much popular demand, you can now add iAds to your iOS applications. iAds works just like any normal view. You’ll create an iAd view by invoking Ti.UI.iOS.createAdView() and placing it at the appropriate location. Make sure you use height and width auto. Until iAds is available, you’ll only see a test ad (assuming you’ve provisioned your application for iAds).

- Support for Common JS. We have added basic support for Common JS where you can use the Common JS to import modules. We don’t fully support the various specifications yet but you can load third-party Common JS modules and use require to load them. Currently, you can drop the modules in your Resources directory and they’ll be picked up. See the updated Kitchen Sink for a simple example. Common JS is supported for both Android and iOS.

- We have deprecated the ImageView property ‘url’ and replace it with the existing ‘image’ property. You can still use the url but you’ll get a warning in the log and may encounter some issues in small cases. Using ‘image’ ensures that all cases should work.

If you find issues, please note them in the comments of this post to help us and others. Please also note we’re only focusing on show-stoppers. Feature requests for 1.4 final aren’t being considered at this time. If you’re a Premium subscriber, please open normal issues in Helpdesk instead of here so we can make sure we respond in the appropriate SLA.

Thanks for everyone’s help in testing.