I like the smell of Swift in the morning…

Embed Javascript files into your iOS App

Posted: | Author: | Filed under: iOS, Xcode | Tags: , | 1 Comment »

When i tried to compile a Javascript file into my iOS App I ran into a strange problem. The javascript files just were not embedded. Whenever I tried to access them using this method:

[[NSBundle mainBundle] pathForResource:@"script.js" ofType:nil];

The method always returned nil. Somehow the javascript file just did not want to be embedded.

At first I could not find out what I was doing wrong, because embedding resources into an App is really easy. Just drag them into your resources folder and you’re done, right? Well, for most file types that’s true. However, with Javascript files things are a bit different:

When compiling the App the compiler treats Javascript files as script files. Meaning that it tries to interpret them instead of just including them into the App bundle uninterpreted.

Here’s how to make the compiler turn a blind eye on the javascript files and just include them into the App bundle without interpreting them:

1. In Xcode’s project navigator (left column) klick on the blue project icon.
2. Select the “Build Phases” tab in the main window
3. Open the “Compile Sources” section
4. Find your Javascript file in the list and remove it.
5. Open the “Copy Bundle Resources” section
6. Add your Javascript file to the list

And that’s it. Now the compiler treats your Javascript file like any other resource file and copies it into the App Bundle.

Xcode 4.5 now creates a warning when you just add a javascript file to your project without removing it from the “Compile Sources” section:

warning: no rule to process file '*FILEPATH*' of type 
sourcecode.javascript for architecture armv7

So the problem is easier to spot now. You still have to fix it manually as I described above.