Link

Using Wikipedia as a data source in your iOS app

Over the weekend I put together a simple periodic table app based on data from Wikipedia, which is fetched and parsed using ObjectiveGumbo. You can head over to my Tumblr blog to read how I did this, or check out the source code on GitHub.

Advertisements

Working in different languages on iOS

The standard language for developing iOS apps is Objective-C and it is what the vast majority of tutorials and sample code for the platform are written in, however over the last year I’ve seen several languages become increasingly dominant on the iOS platform. In this post I’ve tried to review and list as many of the languages as possible. I’ve ignored C/C++ from his post because they are within the Cocoa Touch tool chain already. I’ve also ignored JavaScript and other web technologies because so many platforms and frameworks already exist for them – I’m more interested in compiled platforms.

  • C# is a great language and it is rapidly becoming more popular across many platforms. All C# outside of Microsoft is based off of the Mono project and there are two commercial bindings for iOS. Xamarin allows you to write C# code that integrates with every single Cocoa Touch API (and they have day one updates for each new iOS version, although you can also join their beta programme to get new features at the same time as Apple’s betas, I believe). Unfortunately the free license limits the compiled size of your app but in my experience this isn’t too much of an issue. Being able to write C# proves to be a huge advantage however I’ve found that deploying to device can be quite slow, and the start up time for apps is often a few seconds slower (it is managed rather than native code) and that some patterns from Objective-C such as protocols/delegates don’t transfer over to C# as well – you have to create a subclass of UITableViewDataSource, for example, rather than a class that accepts UITableViewDataSource as a protocol. Alternatively, if you want to write games and don’t care about UIKit, Unity is a great tool that allows you to write your game in C# and deploy across several platforms. I’ve found, again, that the disadvantage of managed code does mean that Unity games tend to be a tiny bit slower than their Objective-C equivalents.
  • Despite Apple’s allegiance to the language in the early OSX days, Java is not a viable option for iOS development however a few bindings do exist. Codename One converts Java Bytecode to native code across several platforms (iOS, Android and Windows Phone) with a native UI. Their site is unclear whether or not they are actually binding to UIKit or if they are creating a native style UI. Alternatively, Google’s J2ObjC converts Java code to Objective-C. This project is very appropriate if you need to use Java for model code rather than UI code and it seems like a sensible choice if you have business logic you need to run on iOS.
  • I had initially expected that there would be very few options for running Python on iOS due to earlier limitations on interpreted languages however evidently the popularity of the language has lead to several options emerging. The first option, PyObjC provides bridging between Objective-C and Python and allows you to write apps that link with UIKit in Python but, like with C#, the differences between the two languages mean that the Python code feels a little clunky. Another option is PyMob, however I can’t find a public version of it to play around with. Finally, Kivy presents itself as a far more viable option for writing iOS games in Python; it makes no attempt to bind with UIKit which brings the benefit that it cross-platform with support for iOS, Android, OSX, Windows and even the Raspberry Pi! I’ve recently enjoyed Pythonista, which is an iOS app that allows you to write Python on your iPad or iPhone. I’ve been using it for about a month and I’ve really enjoyed it – the price tag is definitely worth it.
  • I’ve never really played around with Ruby for a particularly large amount of time but it has always struck me as the interpreted equivalent of Objective-C, which brings the benefit that the syntax doesn’t feel broken when attempting to bind to Objective-C – the MVC style, as well as protocols/delegates is adopted by both languages. RubyMotion links directly with Cocoa/Cocoa Touch and compiles to native code. Unfortunately the license is $200, however compared to the other languages I’ve mentioned here that definitely seems worth it.
  • If you have experience with Flash you would have been initially disappointed by the decision that Flash wouldn’t be available on the iPhone, however thanks to Adobe’s Flash platform with Flex it is now possible to deploy Flash apps to the App Store. This doesn’t strike me as a very good option, however, because there is absolutely no effort to work with the standard iOS frameworks – the aim seems to be to make it possible to deploy your Flash game onto iOS. Furthermore, you lose a lot in performance because the Flash runtime seems to be addicted to battery power, using nearly 100% CPU and every spare bit of RAM – these are some of the reasons, aside from lack of demand – that Flash was removed from Play Store on Android.

When writing this blog post I came across a very common pattern. Often a language will have several bindings available for it, however none of them will be able to maintain the feel of the language (Ruby was the only one that isn’t entirely true of this) because they have to adopt Objective-C idioms which they may not employ themselves. The two best examples of this are protocols/delegates and the way Objective-C functions are named compared to how they are in all other languages. Ultimately, I’ve come to the conclusion that it is probably easiest to build your next iOS app in Objective-C, regardless of how tempting another language may be:

  • There is significantly more documentation available for Objective-C
  • There are disadvantages to working in Objective-C and some things can be achieved in a lot less code in other languages, but otherwise it works perfectly well as a language. With a bit of experience, it really isn’t too challenging to write good re-usable code that runs quickly
  • All the Cocoa Touch frameworks are built in Objective-C and are designed to be interacted with from Objective-C rather than another language with different idioms
  • You are potentially going to be making huge performance sacrifices. In cases when you have an interpreted language like Python or JavaScript this will be an obvious issue but even the performance of C# is radically different on mobile devices to native code. The most simple reason for this is Garbage Collection. Objective-C isn’t GC (the feature was deprecated several years and has never been available on the iPhone) however it uses Automatic Reference Counting instead to manage memory. In some ways this is far more sensible because the “Garbage Collection” effectively happens once at compile time, saving CPU cycles later but on the other hand it may confuse programmers coming from other languages – but this has always been a “feature” of Objective-C :).

Stereoscopic 3D on iOS

Stereoscopic  3D

iOS devices don’t have any kind of 3D option built in, which I’m glad of because it is a pointless gimmick that gives me headaches. Having said that, I quite like the ‘retro’ stereoscopic 3D that could be achieved with red-cyan glasses.

The premise of 3D images is really simple: you have two different images taken it two different positions that are roughly eye distance apart and you then have to find a way of making sure each image only gets into one eye.

About three months ago I was learning the basics of OpenGL ES and I created a dumb Minecraft style world:

'Minecraft' style world

I actually got it pretty well optimised and it can run happily at about 60fps. I then began to look at the code this morning and figured out that stereoscopic rendering wouldn’t be that hard to add to it.

The method is actually really simple:

  • Create two offscreen textures and associated frame buffers* that are the same dimensions as your view.
  • On each frame create two view matrices from your original view matrix with each one shifted a little (I went for about 5mm on an iPad screen)
  • Render the separate view matrices twice into the associated offscreen textures
  • Present both textures blended together with red and blue

The end result (this is the same view as above) looks a bit like this:

iOS Simulator Screen shot 1 Apr 2013 18.00.17

There are a number of disadvantages to this technique. The first is that you can’t go to really high resolutions. I got this running at 60fps on a retina iPad, but I had to render at 1024 * 768 (rather than native 2048 * 1536) without anti-aliasing. The second is that you lose a lot of color information; I had to grayscale my images and even then they appeared quite dull compared to the original image. The third is that this doesn’t scale well across devices because of the distance between the left/red camera and the right/blue camera. I added a pinch to change distance feature so that I could compare between the iOS simulator and real devices.

Despite this, it is actually quite a cool technique although I don’t think that it will become particularly mainstream yet.

iOS Simulator Screen shot 1 Apr 2013 18.16.53 iOS Simulator Screen shot 1 Apr 2013 18.16.58


Update: After some discussion on Reddit I’ve now updated the source a little so that the blending is a little different: the final pixel is made up of the red component of the left pixel and the green and blue components of the right pixel. This maintains color and produces brighter images:

As per request, I’ve also stuck the code on GitHub. It is a little verbose at the moment, but it’s still readable.

*Oh yeah, no GLKit here!

Lessons from iOS dev #1: Threads solve nothing

A bit of prehistory: I first wrote Keep Calm on Android about a year ago and the whole app run on the UI thread. All posters were generated, saved, edited, etc on one thread (unless the system did it on another thread for me, which it generally didn’t). I then learnt the quirks of concurrency on Android and I thought great, now the app should run a little smoother. By last summer when I was writing the first version of Keep Calm on iOS I had fallen in love with concurrency, and even the version currently in the store uses about thirty odd threads (hence why it is so slow, and I’m pushing an update).

Firstly, concurrency is absolutely vital in making a good app. You can’t do network communications, heavy file IO or complex processing on the UI thread because it will begin to become unresposive.

Secondly, don’t use performSelectorInBackground: when you need to do something more than once in the background. It creates a whole new thread which is often completely unnecessary. The superior alternative is to use NSOperationQueue. My current pattern is to use a single background queue across the application because creating additional queues is unnecessary: one NSOperationQueue doesn’t represent a single thread (unless you limit it to) and can run several operations concurrently, so there is no real need to create new queues.

Thirdly, it is far too easy to over-use concurrency. I found myself doing loads of UI operations on another thread which eventually meant I was drawing things about three times and just wasting time and processing power.

I have a new rule for working with concurrency: the view and controller layers (I use MVC, as one should with iOS development) should operate on a single main thread however the controller can instantiate tasks on the Model layer either on the main thread or on my separate NSOperationQueue. My reasons for this are because it reduces complexity, is easy to understand and actually ensures that the app ends up being pretty quick. Obviously there are some tasks that the controller may ‘do’ in a separate thread, however I consider them to be Model tasks.

Lessons from iOS dev #0: Intro

I began doing iOS development around a year ago and since then I’ve gradually improved, having learnt Objective-C entirely from scratch. In this past year I’ve published a few iOS apps (most notably Keep Calm which has had nearly 2M downloads) and I’m gradually moving towards some larger projects, hopefully some games, this summer.

A lot of what I’m going to write over the course of these posts is solely from my own experience. Not all of it will be correct but I’m going to try and focus on things that there isn’t as much documentation on that an iOS developer starting out might not realise. I’ve also learnt a lot of neat tricks as well, so I’ll probably cover those.

Aside from benfitting other people, it also has the advantage that I’m getting stuff out of my head and getting it written down because I’m bound to forget it :).

Things I wanted from Android

A year ago today (March 24th 2012) I published a post on my old blog about things that I wanted from Android. I thought I would do a follow up post now, a year later, to see whether or not those things did ever happen:

  • SVG support everywhere: the key advantage of using SVG for UI graphics is that you don’t have problems with pixel density on the screen. Unfortunately Android still doesn’t support the use of SVG like this, so we are stuck with PNGs for UI graphics. The ADT does now make it easier to import one high-resolution graphic and produce lower resolution versions, and 9-patch PNGs are always an option
  • Better font support: Roboto was introduced with Android 4, but Android still lags behind big time on the number of fonts
  • Higher PPI displays: At the time nothing really competed with the iPhone 4/4S, however now there are a good number of Android phones that do.
  • One Android: I had envisioned that all devices would come with one standard Android. This hasn’t happened, but the growing popularity of Nexus devices has lead to more devices using stock/Google Android
  • Google Play gift cards: these have been introduced, and sales have increased as a result 🙂
  • Better integration between Eclipse and Google Play: when you finish producing an iOS app, it only takes a couple of clicks in Xcode to send it off to Apple. With Android, you still have to produce an APK and upload it via the web interface. Obviously this isn’t much of a pain, but I like Apple’s simple system.
  • OTA updates: obviously automatic updating of the Android system is something that vendors do rather than Google (aside from Nexus devices, and their increasing dominance is a very good thing for developers) however the difference between users on the latest version of iOS and Android is still huge. Interestingly, long before the original post was written Google had announced in 2011 the ‘Android Update Alliance’ which promised timely updates by manufactures every 18 months after a device release. This never happened, and I should imagine that the reasoning is that the devices of early 2011 would have been running Android 2.x, whereas the devices released last summer would have been running Android 4.x which required much higher performance
  • A better emulator: today the emulator is much faster, especially thanks to the introduction of GPU/hardware acceleration and a new Intel (rather than ARM) image that makes the execution of apps a hell of a lot faster

Obviously Android still hasn’t met all of these requirements and I didn’t think it will meet some of these for quite some time, if ever. I’m pleased, however, to see that changes have happened and that they have worked. Here is what I would still like from Android, from a developing perspective:

  • Faster development time: This is most likely due to my lack of experience with Android development compared to iOS development, however I’ve found that I can write an iOS app much faster than I can write an Android app. Setting up the UI takes longer, linking the UI to code takes longer, the IDE is slower, the emulator* is slower, deploying the app takes longer and the export process takes longer
  • A better IDE: Eclipse has been a great IDE and it is still very usable, however IntelliJ seems to have a lot more useful features
  • Java?: I’m not sure that we need to stick with Java for Android development at all. Xaramin have done an awesome job at bringing C# to Android, and they claim that performance is just as good (if not better) than Dalvik. That’s impressive, and with a better IDE, nicer language and full API support (but high cost) it certainly is a viable option

*The iOS ’emulator’ is actually a simulator. When you test iOS apps on desktop it compiles an x86 version instead of an ARM version.

Generating large Fibonacci numbers with C++

EDIT: This is a really, really stupid way of handling large numbers in C++. It is a nice proof of concept in terms of how you can do the ‘unit addition’ that you might have learnt in school pragmatically, but if you really want to be handling large numbers you need to be using something like GMP.

This morning I set myself the challenge of writing a Python program to generate large Fibonacci numbers, however I later rewrote it in C++ and it worked a lot better, so I’ve stuck with the C++ version. In fact, execution times were up to 60 times faster in C++.

The main problem I had is the limitations of standard integer types in C++. A 32bit, unsigned long will limit you to just over 4 billion. A 64bit, unsigned long will limit you to roughly 1.844 x 10^19, which gives you about 20 digits. The problem is that the 48th and 93rd numbers in the Fibonacci sequence will exceed these limits respectively. Therefore I created an alternative solution.

I basically ended up storing numbers in strings and then splitting them into a single character array before adding them, effectively doing column addition digitally. Whilst this is ridiculously inefficient for the smaller Fibonacci numbers (i.e. less than 2^64), it will happily allow you to calculate numbers significantly higher than the limits of your CPU.

Annoyingly the executable is quite large (on Windows) and I have to include the vector library so I can have variable length arrays but other than that minor issue the program will run ridiculously quickly – I can calculate the first 50,000 in a matter of seconds although anything exceeding this takes significantly longer.

If you’re using GCC then you could probably adapt this and reduce executable size by replacing the vector stuff with VLAs but I was using the VC++ compiler so I couldn’t and I wanted this to work cross platform. Here is the full source code (I’m going for Apache license even though there isn’t much of it):

/*
 Copyright 2012 Programming Thomas
Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 To compile with VC++ use the VS command line and cl /Ox fibonacci.cpp
 To compile with G++ use g++ -o fibonacci fibonacci.cpp
*/
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
std::string intToString(int s)
{
 std::string toReturn = "";
 while (s > 0)
 {
 char v = s % 10 + 48;
 toReturn = v + toReturn;
 s = (s - (s % 10)) / 10;
 }
 return toReturn;
}
int stringToInt(std::string s)
{
 int v = 0;
 for (int n = 0; n < s.length(); n++)
 {
 if (s[n] >= 48 && s[n] < 58) v = (v * 10) + s[n] - 48;
 else break;
 }
 return v;
}
std::string add(std::string a, std::string b)
{
 std::vector<char> aList;
 int n;
 for (n = 0; n < b.length(); n++) aList.push_back(b[n] - 48);
 int offset = b.length() - a.length();
 for (n = 0; n < a.length(); n++) aList[n + offset] += a[n] - 48;
 for (n = aList.size() - 1; n > 0; n--)
 {
 aList[n - 1] += (aList[n] - aList[n] % 10) / 10;
 aList[n] = aList[n] % 10;
 }
 std::string toReturn = intToString(aList[n]);
 for (n = 1; n < aList.size(); n++) toReturn += 48 + aList[n];
 return toReturn;
}
int main(int argc, char* argv[])
{
 if (argc > 1)
 {
 int SIZE = stringToInt(argv[1]);
 std::cout << "Going to calculate the first " << SIZE << " terms." << std::endl;

 std::string a = "1", b = "1", c;
 std::ofstream file;
 file.open(("fib" + intToString(SIZE) + ".txt").c_str());
 file << "1";
 for (int i = 2; i <= SIZE; i++)
 {
 file << std::endl << b;
 c = add(a,b);
 a = b;
 b = c;
 }

 std::cout << "Calculated values and written to file";
 file.close();

 return 0;
 }
 else
 {
 std::cout << "You should supply a number of items (fibonacci 100 for example)" << std::endl;
 return 1;
 }
}

Please click here for the raw source file and here for the EXE. To use the program, open up a command line and execute fibonacci followed by the total number of numbers you wish to generate. It will then output this to an appropriately named text file.

Note that because a rather large amount of text gets written to a file whilst the program is running (it isn’t possible to cache it before writing because generating anything above 100,000 items is going to use a lot of RAM) it is probably worthwhile running this on a reasonably fast hard disk or SSD rather than a USB drive.

Drawing stars with HTML5 Canvas

Update: I’ve since written a slightly different version that can draw n-sided polygons.


I was searching around for some decent HTML5 demos earlier and I noticed that there weren’t any particularly good tutorials or functions for drawing regular stars. Obviously Canvas is fine for drawing polygons and so I was able to produce this very simple function that uses the rotate() function to position the points:

function star(ctx, x, y, r, p, m)
{
    ctx.save();
    ctx.beginPath();
    ctx.translate(x, y);
    ctx.moveTo(0,0-r);
    for (var i = 0; i < p; i++)
    {
        ctx.rotate(Math.PI / p);
        ctx.lineTo(0, 0 - (r*m));
        ctx.rotate(Math.PI / p);
        ctx.lineTo(0, 0 - r);
    }
    ctx.fill();
    ctx.restore();
}

You call the function by using star(canvas, x of center, y of center, radius, number of points, fraction of radius for inset). Here are some examples. To create a five point star, therefore, you call star(ctx, 100, 100, 90, 5, 0.5). Here is an example of what that looks like:

Obviously because the function doesn’t actually set styles or shadows but this isn’t too difficult to implement. Here is a live demo of the star being drawn.

Hello, world

I’ve decided to move the majority of my content over to this blog because it has a decent name and matches everything else that I do online. I’ve aimed to create lots of information about my apps and programming in general so please subscribe to check out all the fascinating projects that I’ve been working on. For more information check out the following links: