July 3, 2014

Awesome Samples to Jumpstart F# Mobile Development


Throughout the week we have seen a wide assortment of F# samples and applications that you can use to jump start your F# mobile development. Here are a few new resources available to developers, including full sample applications comprised of beautiful F# source code.

F# Tutorial

Starter Guides

With the release of Xamarin 3, we brought first class F# support to developers inside of Xamarin Studio. To go along with that, we also have great getting started documentation, along with a few other fantastic resources to get you going:

Mobile App Samples

F# Shallow App
In addition to documentation here are a few open source F# mobile apps that you can run right away.


Based on popular dating apps, Shallow is a great example of using beautiful animations built into iOS, that you can take advantage of with a few lines of code in F#.

For a full break down of Shallow’s features and introduction to its F# goodness be sure to see the full blog post by Xamarin’s David Siegel, and its GitHub repo.

Tasky F#

Recently announced Xamarin Evolve speaker and F# enthusiast Rachel Reese wrote an amazing introduction to mobile development in F# post. Not only did she break down all of the benefits of F#, but also built out a full Task taking app, Tasky F#, that is completely open source on GitHub.

Xamarin Store

anuj f sharp shirtWhen we kicked off F# week, we released a brand new version of the Xamarin Store app for iOS and Android. This is where you can get your very own F# t-shirt shipped for FREE directly to your doorstep for trying Xamarin and running your first F# app. This is a beautiful application with elegant animations such as Ken Burn’s effects on images. Download the source code today and get your very own F# t-shirt.

Show us your F# Hacks!

These are a few great examples to help kick start your F# mobile development with Xamarin. We are sure might have your own F# tips and tricks to share with developers, so head over to our Community Forums and share your own F# hacks!

July 2, 2014

Headed to the Capitol for Microsoft WPC 2014


Xamarin is headed to the capitol to meet with our rapidly growing network of partners, and to strike new relationships at Microsoft’s premier partner event this July.  We will be in Washington, D.C for Microsoft’s Worldwide Partner Conference at booth #828 to meet our community, learn about your apps, and connect with our partners.  


Join Xamarin for food and drinks during WPC week on Tuesday, July 15th from 7:30 pm to 10:30 pm. We’ll have a selection of delicious drinks and appetizers, and of course, plenty of mobile development talk. We look forward to seeing you there!

When: Tuesday, July 15th, 7:30pm – 10:30pm

Where: Redline Gastrolounge, 707 G Street Northwest, Washington, D.C. 20001


Not at the Worldwide Partner Conference but in the DC area?  Stop by anyway! You and your friends are welcome. Make the most of your time at WPC and schedule dedicated time with the Xamarin partner team while you’re in town for the conference.

July 1, 2014

Introduction to F# with Xamarin, Part II


rachel-reeseRachel Reese is a long-time software engineer and math geek who recently relocated to Nashville, TN to work at Firefly Logic. Rachel is an ASPInsider and an F# MVP. You can catch her at Xamarin Evolve 2014, the largest conference for cross-platform mobile development.

This blog post is part of our continuing celebration of F# Week at Xamarin! Celebrate by getting your own F# t-shirt! Yesterday, Rachel gave us an “Introduction to F# with Xamarin”. Today, she takes us through building a task management app with F# and Xamarin.

Getting Started with iOS Development
Yesterday, we took a look at the benefits of F# by building much of the data layer for the F# version of the task-management app Tasky. Today, let’s complete that, add a couple of views, and we’ll be up and running with an F# version of Xamarin’s favorite task app!

In Xamarin Studio, create a new F# iOS Single View Application named “Tasky”. Xamarin Studio will create a solution for us, with two important files:

    1. AppDelegate.fs – This is the heart of the application. The Main module defines an application’s entry point, while the AppDelegate type inherits from UIApplicationDelegate, which provides such application lifecycle events as ApplicationDidFinishLaunching and ApplicationWillTerminate. From AppDelegate, we’ll define which view controller should load first. In this case, because the application is named Tasky, the first view controller that’s called is TaskyViewController.fs.
    2. TaskyViewController.fs – This is the project’s first view controller. This is inherited from UIViewController, and the main overridable methods here handle the view lifecycle. For example: ViewDidLoad, DidReceiveMemoryWarning, DidRotate, ViewWillDisappear, etc.

If we run the project at this point, before making any changes, it will load a blank, black screen. Let’s make it do a bit more. We will start by setting up navigation. Open AppDelegate.fs and update the RootViewController to the following:

window.RootViewController <- new UINavigationController (new TaskyViewController ())

Wrapping the TaskyViewController in a UINavigationController will allow a user to navigate back from the update task screen (once we create it). In other words, that screen will display a back button allowing return to the task list. That finishes off the changes we’ll need to make for Tasky in AppDelegate.fs.

Next, let’s work on the main view controller. Open TaskyViewController.fs, and we’ll add an event handler in ViewDidLoad, for adding a new task from a “+” button on the navigation bar.

let addNewTask =
    new EventHandler (fun sender eventargs ->
        this.NavigationController.PushViewController (new AddTaskViewController (), true)
this.NavigationItem.SetRightBarButtonItem (new UIBarButtonItem (UIBarButtonSystemIcon.Add, addNewTask), false)

At this point, we’ll also need to create a nearly empty AddTaskViewController.fs, inherited from UIViewController, like so:

type AddTaskViewController () =
    inherit UIViewController ()
    override this.ViewDidLoad () =
        base.ViewDidLoad ()

Our final project structure will look like this:


Creating and Populating with Data

Now that the navigation is set up, let’s build the task list itself. First, create the UITableView:

let table <- new UITableView ()

Next, within the ViewDidLoad method, set the view’s frame to be the full screen, and add the table to the view.

table.Frame <- this.View.Bounds
this.View.Add table

Displaying the table was the easy part. Next, we’ll need to fill the table with data. To help do this, we need to create a UITableViewSource. In our case, we take in the list of tasks that are returned from the SQLite Type Provider, as well as our navigation controller. We will need to include the navigation controller as a parameter, so that we can navigate when the user clicks a row in the table. We also copy the task list locally, and set the cell identifier to a unique name for this cell type. It’s possible to load a mix of different cell types (with completely varied layouts) into an iOS table, and this identifies which one is being loaded.

type TaskDataSource(tasksource: task list, navigation: UINavigationController) =
    inherit UITableViewSource ()
    let tasks = new List<task> (taskSource)
    member x.cellIDentifier = "TaskCell"

Once we’ve defined those, there are two methods we absolutely must override in TaskDataSource: RowsInSection, and GetCell. RowsInSection returns the total number of rows that the table contains; GetCell dequeues or creates a new UITableViewCell, then populates that cell with the correct data for that row. [For more information on dequeuing, see the “Note on Cell Reuse” in the Xamarin docs, above.]

override x.RowsInSection (view, section) = tasks.Count
override x.GetCell (view, indexPath) =
    let t = tasks.[indexPath.Item]
    let cell =
        let newCell = view.DequeueReusableCell x.cellIdentifier
        match newCell with
            | null -> new UITableViewCell (UITableViewCellStyle.Default, x.cellIdentifier)
            | _ -> newCell
    cell.TextLabel.Text <- t.Description

With these added, let’s jump back to the TaskyViewController type. We need to override ViewWillAppear, to set the newly created TaskDataSource to be the UITableView source. We also must reload the data each time the view appears. Using the GetIncompleteTasks method we created in the type providers section, we should now be able to run Tasky and load the tasks.

override this.ViewWillAppear animated =
    base.ViewWillAppear animated
    table.Source <- new TaskDataSource (Data.GetIncompleteTasks (), this.NavigationController)
    table.ReloadData ()

This will give us the basic set up to load a table of tasks, but we aren’t yet able to navigate to a detail page upon selecting a row, nor are we able to delete with a swipe in from the right.

Swipe to Delete
Adding the ability to swipe delete is only a matter of adding two more overrides into the TaskDataSource type.

  • CanEditRow is, logically, whether or not that row can be edited.
  • CommitEditingStyle handles the deletion. First, delete the task from the data source; second, remove the task from the tasks list; finally, delete that row from the view.
override x.CanEditRow (view, indexPath) = true
override x.CommitEditingStyle (view, editingStyle, indexPath) =
    match editingStyle with
        | UITableViewCellEditingStyle.Delete ->
          Data.DeleteTask tasks.[indexPath.Item].Description
          tasks.RemoveAt (indexPath.Item)
          view.DeleteRows ( [|indexPath|], UITableViewRowAnimation.Fade)
        | _ -> Console.WriteLine "CommitEditingStyle:None called"

Selection and Navigating
The final step in the TaskyViewController functionality is to handle navigation. To select a row and navigate to a detail page for that row, we only need to override the RowSelected method. In this case, we first want to deselect the row (so that when we return to the view, the row doesn’t remain selected), and then push the new view controller. We’re using the AddTaskViewController, which handles both adding and updating tasks.

override x>RowSelected (tableView, indexPath) =
    tableView.DeselectRow (indexPath, false)
    navigation.PushViewController (new AddTaskViewController (tasks.[indexPath.Item], false), true)

The above code modifies the constructor of the AddTaskViewController (created previously) to accept a current task, as well as a Boolean determining whether or not that task is a new task. We’ll update this in the next section.

Creating a Non-Table View
We’re almost done now; we just need to add a quick form to handle adding and updating a task. Let’s start by updating the constructor to accept a task and a Boolean, as just mentioned. To do this, we need to modify the AddTaskViewController type to take in the new parameters. We’ll also add a second, parameterless constructor, which creates an instance of the controller with some defaults – specifically: Description should be empty, Complete should be false, and the isNew Boolean should be true, exactly as one would expect with a brand new task.

type AddTaskViewController (task:task, isNew:bool) =
    inherit UIViewController ()
    new () = new AddTaskViewController ({Description=""; Complete=false}, true)
    override this.ViewDidLoad () =
        base.ViewDidLoad ()

Now, let’s move into the ViewDidLoad method. Create a new subview to which we will add our fields, and set the background color to white.

let addView = new UIView (this.View.Bounds)
addView.BackgroundColor <- UIColor.White

From here, we simply add and position our form elements. We’ll start with a UITextField for the Description, and a UISwitch with corresponding UILabel for our Complete field. We also add an event handler to handle setting Complete on our task when the switch is toggled.

let description = new UITextField (new RectangleF (20.f, 64.f, 280.f, 50.f))
description.Text <- task.Description
description.Placeholder <- "task description"
addView.Add description
let completeLabel = new UILabel (new RectangleF (20.f, 114.f, 100.f, 30.f))
completeLabel.Text <- Complete
addView.Add completeLabel
let completeCheck = new UISwitch (new RectnagleF (120.f, 114.f, 200.f, 30.f))
completeCheck.SetState (task.Complete, false)
let changeCompleteStatus =
    new EventHandler (fun sender eventargs ->
        task.Complete <- completeCheck.On
completeCheck.TouchDragInside.AddHandler changeCompleteStatus
addView.Add completeCheck

Now that the input part is complete, we need to be able to save new tasks, along with a corresponding label to indicate the operation has completed. Depending on whether or not the task is new, we call the appropriate Add or Update function in our Data file, and then print “Added” or “Updated”.

let addedLabel = new UILabel (new RectangleF (20.f, 214.f, 280.f, 50.f))
addView.Add addedLabel
let addUpdateButton = UIButton.FromType (UIButtonType.RoundedRect)
addUpdateButton.Frame <- new RectangleF (20.f, 164.f, 280.f, 50.f)
let addUpdateHandler =
    new EventHandler (fun sender eventargs ->
        match isNew with
            | true ->
                Data.AddTask description.Text
                addedLabel.Text <- "Added!"
            | false ->
                Data.UpdateTask description.Text completeCheck.On
                addedLabel.Text <- "Updated!"
        description.Text <- ""
addUpdateButton.TouchUpInside.AddHandler addUpdateHandler
addUpdateButton.SetTItle ("Save", UIControlState.Normal)
addView.Add addUpdateButton

Since the label was added to indicate that saving is complete, we need to clear the text when we want to add a new task, to minimize confusion, and make it obvious that the new task has also been added. To that end, we add a clear label function that is called when the user clicks back into the Description field.

let clearLabel =
    new EventHandler (fun sender eventargs ->
        addedLabel.Text <- ""
description.TouchDown.AddHandler clearLabel

Finally, we simply need to add the subview that we’ve been populating to the main view, and we’re done!

this.View.Add addView

We have just built an F# version of Tasky, Xamarin’s favorite task-management app! You can get the bits on GitHub and follow me on Twitter @RachelReese.


Introduction to F# with Xamarin


rachel-reeseRachel Reese (@RachelReese) is a long-time software engineer and math geek who recently relocated to Nashville, TN to work at Firefly Logic. Rachel is an ASPInsider and an F# MVP. You can catch her at Xamarin Evolve 2014, where you can learn from industry leaders and Xamarin expertsto advance your projects and career.

This blog post is part of our continuing celebration of F# Week at Xamarin! Celebrate by getting your own F# t-shirt!

Why F#?
Let’s first dig into a few of my favorite reasons to consider F# for your next Xamarin project: type inference, units of measure, type providers, as well as the ever-crucial clarity and conciseness of code.

Type Inference
People often underestimate the benefits of type inference, but the ability to clear out the type definitions from code and concentrate on the code itself, instead of all the clutter around the declaration, is tremendous. Consider this example (from here, via here):


    public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2)
        return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) =>
            Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)),
                 l(t2.Left), r(t2.Right)),
            x => y => null, tree)(tree2);

The equivalent F# is much easier on the eyes. The code itself might still be incomprehensible, but it is at least not drowning in required type definitions. It’s no longer necessary to filter through all the extra information before trying to understand what’s happening.

let DiffTree(tree,tree2) =
    XFoldTree (fun x l r t t2 ->
        let (Node(x2,l2,r2)) = t2
        Node((x2,t===t2), l l2, r r2)) (fun _ _ -> Leaf) tree tree2

For more information on type inference, see the F# for Fun and Profit website. There are some fabulous examples of how it works, and how to troubleshoot the errors that sometimes show up.

Units of Measure
Units of measure are types that allow one to add unit information to a numeric type in F#. Once a value is tagged with a unit type, it can only be combined with other values that have that same unit. For example, if we want to track distances and times, it’s possible to create:

[<Measure>] type s
[<Measure>] type m

Then, when we define a new value, we can easily associate our new unit with it:

let time = 30<s>
let distance = 10<m>

The compiler will error if we try to add the two values, but it is possible to divide them:

let velocity = distance/time

If we hover over this declaration, the tooltip for this value will show:

val velocity : int<m/s>

All scientific computing will benefit from enforcing units (game physics!) but it doesn’t have to be exclusively the domain of science. Think about using pixel, USD, or Fahrenheit, among others!

It’s also possible to use generic units of measure in a function. For example, we’d like to calculate a perimeter, given some distances. We can declare the function like so:

let perimeter = (x:int,<'distance>) (y:int<'distance>) = 2*x + 2*y

In this manner, we’re able to utilize one function for many different units of measure. As long as the units for a single given call are the same, the code will compile. However, the compiler will still throw an error if we try to call perimeter with two different units. To wit:

// Compiler error: The unit of measure 'ft' does not match the unit of measure 'm'
let p_1 = perimeter 10<m> 4<m>
let p_2 = perimeter 2<ft> 3<m>

Type Providers
Type providers are a mechanism that allows F# code to access typed information from external data sources with no code generation, all in just a few lines of code. They are a revolution in data access! F# was the first enterprise-grade language to have type providers, and is still the only .NET language to have them. So, if we want to use a type provider in our Xamarin project, we’ll need to use F#!

There are many, many type providers available, but I’ll concentrate on two that are especially useful with Xamarin projects today – the SQLProvider and the Freebase Provider.


The SQLProvider provides access to MS SQL Server, SQLite, PostgreSQL, Oracle, MySQL, ODBC, and MS Access databases. Since SQLite is a tremendously common database to hook up with both iOS and Android applications, let’s take a look at what’s required to use the SQLProvider type provider to connect to a SQLite database in an F# Xamarin project!

First, we declare a type. We’ll need to change this to include the connection string, as well as the path to the mono.sqlite.dll.

type sql = SqlDataProvider

At this point, we’re ready to go. To show off the SQLite provider, let’s build a quick port of the Xamarin Tasky app (see original here). We’ll need to create just a couple of functions for our data layer: GetIncompleteTasks, AddTask, UpdateTask, and DeleteTask. However, first we need to get the data context:

let ctx = sql.GetDataContext ()

Every time we type `ctx`, we’ll get code completion on the remaining pieces:


As well as tooltips, which show that the information coming back from SQLite is fully typed:


Once we have set up the data context, creating the methods we need is as easy as pie. Let’s declare a type for the return data, to use in our queries:

type task = { Description : string; mutable Complete : bool; }

Then, to return the incomplete tasks, we use the familiar query syntax:

let GetIncompleteTasks () =
    query { for data in ctx.``[main].[tasks]`` do
                where (data.complete = 0L)
                select {Description=data.task; Complete = false}}
            |> Sql.toList

This returns an F# list of tasks, where complete is false. That’s it. No messy ORMs to contend with, no long data access libraries to futz with; we only need a database connection and a query. Adding a task is just as easy, we need to create a new task, update the two fields (“<-” is the F# assignment operator), and finally, submit our updates.

let AddTask description =
    let newTask = ctx.``[main].[tasks]``.Create()
    newTask.task <- description
    newTask.complete <- 0L


The Freebase.com web site describes itself as a community-curated database. They currently have a list of nearly 44 million topics, and over 2.5 billion facts. Connecting our app in to all their data is simple, with the Freebase type provider! We merely need to get the context, and start querying.

The Freebase database is especially exciting because the data is returned with additional units of measure. In the example above, when the results are returned, and in the tooltips, we can see that the particle charge is shown in coulombs!


As with all type providers, the Freebase provider also has code completion into the structure of our data source. It frees us up to explore the data!


Keep an eye out on the Xamarin Blog for Part 2 of Getting Started with Xamarin and F#, where I’ll discuss using F# to build amazing cross-platform, native apps.

June 30, 2014

Run an F# app, get an F# shirt


Our Run a C# app, get a C# shirt promotion has been a great success, as thousands of developers in over 95 countries have ordered these C# shirts.

With Xamarin 3 we made F# a first class citizen. You can now use Xamarin Studio to build amazing Android and iOS apps in your favorite functional language. For the last month, the world has lifted the stigma of trying to be functional in an object oriented world.

Today, we are excited to announce “Run an F# app, get an F# shirt!” Download the F#-ified Xamarin Store app, run it, and an F# shirt will be on its way to you!

This app provides both a native experience on Android and iOS, while being written entirely in F#. It’s a great resource to familiarize yourself with the language or the platforms.

F# Shirts!

Why F#?

F# is a modern strongly-typed functional programming language for the .NET platform.

It brings the state of the art in functional programming expressiveness and succinctness while allowing you to access all the APIs available in .NET, Android and iOS. This is the kind of language that powers magical places like Equestria.

To help you get started, we have put together full F# documentation and guides.

F# Week

To celebrate the succinctness of F#, we are going to devote this short week to daily nuggets of F# goodness in the mobile world. Stay tuned!\

June 27, 2014

Supercharge your Amazon Android apps


The wide range of Amazon Android powered devices create a unique opportunity for Xamarin developers. The Fire TV, Tablets, and now Phone all have great features with brand new SDKs for developers to take advantage. On the Fire Phone you can add Dynamic Perspective and Firefly features to your app and on the Fire TV you can add special notifications or game pad support with just a few lines of code. You can find all of these specific SDKs for you to use in your Xamarin.Android apps right on our Component Store, which are full of samples and documentation for you to get started with.

Amazon Fire Devices

Amazon Fire OS

While some of these features are specific to each device, Amazon devices all run on the Amazon Fire OS and have a unique set of APIs for you to take advantage of. The Amazon Fire OS component allows you to add a wide range of Amazon services to your app including:

  • Amazon Maps – Add interactive maps to your apps and delight users with custom overlays.
  • Amazon GameCircle – Sync your game data across devices and platforms to improve player experience and retention.
  • Amazon In-App Purchases – Sell digital content and subscriptions including in-game currency and more, from within your apps.
  • Amazon Device Messaging – Send push notifications from the cloud to Kindle Fire devices that run your app.

Sound Matters

Dolby Audio Xamarin ComponentAnother distinguishing feature of the Fire Phone and HDX tablets is enhanced audio with Dolby Audio. Dolby Audio sets these devices along with Android devices from Samsung, ZTE, Lenovo, and Acer apart with great sound when playing music, video, or games. The ability to take advantage of this unique feature has been only available to the device manufacturer until now. Inside of your Xamarin.Android app or game you can now take advantage of Dolby Audio with the new Dolby Audio Component. The Dolby Audio Component will give your sound a boost with custom profiles optimized for music, games, voice, and video with just a few lines of code. If you haven’t implemented audio playback in your apps before, be sure to read through our previous blog on Background Audio Streaming and Lock Screen Music Controls.

Getting Started

The first thing you will need to do is add the new Dolby Audio Component into your Xamarin.Android app. This will add the Dolby Audio API along with samples and a getting started guide.


After adding the component there are only two items to implement to get Dolby Audio in your application. First, you will need to implement


on your Activity or Service. This will add several methods into your application to detect changes in the Dolby Audio Processor.

public class MusicActivity : Activity, IOnDolbyAudioProcessingEventListener
  protected override void OnCreate (Bundle bundle) {
  public void OnDolbyAudioProcessingClientConnected () {
  public void OnDolbyAudioProcessingClientDisconnected () {
  public void OnDolbyAudioProcessingEnabled (bool enabled) {
  public void OnDolbyAudioProcessingProfileSelected (DolbyAudioProcessing.PROFILE profile){


With our Activity setup to handle Dolby Audio Processing the last thing we need to do is enable it in our app using the


class. This will enable us to turn Dolby processing on and off and even change profiles.

public class MusicActivity : Activity, IOnDolbyAudioProcessingEventListener
  static DolbyAudioProcessing dolbyAudioProcessing;
  protected override void OnCreate (Bundle bundle) {
  private void CreateDolbyAudio() {
    if (dolbyAudioProcessing == null)
      dolbyAudioProcessing = DolbyAudioProcessing.GetDolbyAudioProcessing (this, DolbyAudioProcessing.PROFILE.Music, this);
    if (dolbyAudioProcessing == null) {
      Console.WriteLine ("Dolby Audio does not exist on this device.");

If Dolby audio exists on the Android device, calling GetDolbyAudioProcessing will return the processor else it will be null. This means even if your app is installed on a device without Dolby Audio there is no effect on your app, but if there is then you will get a great audio boost with customizations.

Enhanced Profiles

After Dolby Audio is enabled in your application you can also customize the Dolby Audio Processor with different audio profiles for your application. You can choose from Music, Video, Voice, and Game, so there is surely a profile for you. In this sample I simply toggle between all of the profiles when I click a button:

private void ToggleDolbyProfile() {
  if (dolbyAudioProcessing == null || !dolbyAudioProcessing.Enabled)
  var newProfile = DolbyAudioProcessing.PROFILE.Music;
  var newProfileText = "Music";
  if (dolbyAudioProcessing.SelectedProfile == DolbyAudioProcessing.PROFILE.Music) {
    newProfile = DolbyAudioProcessing.PROFILE.Game;
    newProfileText = "Game";
  } else if(dolbyAudioProcessing.SelectedProfile == DolbyAudioProcessing.PROFILE.Game){
    newProfile = DolbyAudioProcessing.PROFILE.Movie;
    newProfileText = "Movie";
  } else if(dolbyAudioProcessing.SelectedProfile == DolbyAudioProcessing.PROFILE.Movie){
    newProfile = DolbyAudioProcessing.PROFILE.Voice;
    newProfileText = "Voice";
  } else if(dolbyAudioProcessing.SelectedProfile == DolbyAudioProcessing.PROFILE.Voice){
    newProfile = DolbyAudioProcessing.PROFILE.Music;
    newProfileText = "Music";
  dolbyAudioProcessing.SetProfile (newProfile);
  Toast.MakeText(this, "Dolby profile: " + newProfileText, ToastLength.Short).Show();

It really is that simple to add enhanced audio with Dolby in your apps with just a few lines of code. With the launch of the Fire Phone coming soon, adding new features can really set your app apart in the marketplace. Be sure to enter our Ship an Amazon Fire Phone App Contest going on right now for your chance to win your very own Fire Phone or Fire TV!

June 26, 2014

Lights, Camera, Action – 3D in iOS 8 with Scene Kit


Scene Kit is a powerful 3D graphics API that makes working with 3D a snap. It was first introduced in OS X 10.8, and has now come to iOS 8. With Scene Kit creating immersive 3D visualizations and casual 3D games no longer requires expertise in OpenGL. Building on common scene graph concepts, Scene Kit abstracts away the complexities of OpenGL and OpenGL ES, making it very easy to add 3D content to an application. However, if you are an OpenGL expert, Scene Kit has great support for tying in directly with OpenGL as well. It also includes numerous features that complement 3D graphics, such as physics, and integrates very well with several other Apple frameworks, such as Core Animation, Core Image and Sprite Kit.

3D earth

Scene Kit is extremely easy to work with. It is a declarative API that takes care of rendering. You simply set up a scene, add properties to it, and the magic of Scene Kit brings it all to life.

To work with Scene Kit you create a scene graph using the SCNScene class. A scene contains a hierarchy of nodes, represented by instances of SCNNode, defining locations in 3D space. Each node has properties such as geometry, lighting and materials that affect its appearance.

node tree

To make a scene appear on screen, you add it to an SCNView by assigning it to the view’s Scene property. Additionally, if you make any changes to the scene, SCNView will update itself to display the changes.

scene = SCNScene.Create ();
sceneView = new SCNView (View.Frame);
sceneView.Scene = scene;

Scenes can be populated from files exported via a 3d modeling tool, or programmatically from geometric primitives. For example, this is how to create a sphere and add it to the scene:

sphere = SCNSphere.Create (10.0f);
sphereNode = SCNNode.FromGeometry (sphere);
sphereNode.Position = new SCNVector3 (0, 0, 0);
scene.RootNode.AddChildNode (sphereNode);

Let There Be Light

At this point the sphere won’t display anything because there is no light in the scene. Lights in Scene Kit are created by attaching SCNLight instances to nodes. There are several types of lights ranging from various forms of directional lighting to ambient lighting. For example the following code creates an omni directional light on the side of the sphere.

// omni-directional light
var light = SCNLight.Create ();
var lightNode = SCNNode.Create ();
light.LightType = SCNLightType.Omni;
light.Color = UIColor.Blue;
lightNode.Light = light;
lightNode.Position = new SCNVector3 (-40, 40, 60);
scene.RootNode.AddChildNode (lightNode);

Omni directional lighting produces a diffuse reflection resulting in an even lighting, sort of like shining a flashlight. Creating ambient light is similar, although it has no direction as it shines equally in all directions. Think of it like mood lighting :)

// ambient light
ambientLight = SCNLight.Create ();
ambientLightNode = SCNNode.Create ();
ambientLight.LightType = SCNLightType.Ambient;
ambientLight.Color = UIColor.Purple;
ambientLightNode.Light = ambientLight;
scene.RootNode.AddChildNode (ambientLightNode);

With the lights in place, the sphere is now visible in the scene.


Adding a Camera

Adding a camera (SCNCamera) to the scene changes the point of view. The pattern to add the camera is similar. Create the camera, attach it to a node and add the node to the scene.

// camera
camera = new SCNCamera {
	XFov = 80,
	YFov = 80
cameraNode = new SCNNode {
	Camera = camera,
	Position = new SCNVector3 (0, 0, 40)
scene.RootNode.AddChildNode (cameraNode);

As you can see from the code above, Scene Kit objects can be created using constructors or from the Create factory method. The former allows using C# initializer syntax, but which one to use is largely a matter of preference.

With the camera in place, the entire sphere is visible to the user.


You can add additional lights to the scene as well. Here is what it looks like with a few more omni-directional lights:


Additionally, by setting sceneView.AllowsCameraControl = true, the user can change the point of view with a touch gesture.


Materials are created with the SCNMaterial class. For example to add an image onto the sphere’s surface, set the image to the material’s diffuse contents.

material = SCNMaterial.Create ();
material.Diffuse.Contents = UIImage.FromFile ("monkey.png");
sphere.Materials = new SCNMaterial[] { material };

This layers the image onto the node as shown below.


A material can be set to respond to other types of lighting too. For example, the object can be made shiny and have a its specular contents set to display specular reflection, resulting in a bright spot on the surface.


Materials are very flexible, allowing you to achieve a lot with very little code. For example, instead of setting the image to the diffuse contents, set it to the reflective contents instead.

material.Reflective.Contents = UIImage.FromFile ("monkey.png");

Now the monkey sits visually within the sphere, independent of the point of view, creating a monkey in a psychedelic 1960s sphere so to speak.

spinning monkey


Scene Kit is designed to work well with Core Animation. You can create both implicit or explicit animations. When creating an implicit animation, Scene Kit provides its own transition class, SCNTransaction.

Here’s a example that rotates the sphere:

SCNTransaction.Begin ();
SCNTransaction.AnimationDuration = 2.0;
sphereNode.Rotation = new SCNVector4 (0, 1, 0, (float)Math.PI * 4);
SCNTransaction.Commit ();


You can animate much more than rotation though. Many properties of Scene Kit are animatable. For example, the following code animates the material’s Shininess to increase the specular reflection.

SCNTransaction.Begin ();
SCNTransaction.AnimationDuration = 2.0;
material.Shininess = 0.1f;
SCNTransaction.Commit ();


As you can see, Scene Kit is incredibly easy to use. This post just scratches the surface though. There are a wealth of additional features including constraints, physics, declarative actions, 3D text, depth of field support, Sprite Kit integration and Core Image integration to name just a few. It’s exciting to see this API come to iOS 8.

The source code from this post is available here.

Discuss this blog post in the Xamarin Forums

June 25, 2014

Show Me the XAML


Xamarin.Forms brings the eXtensible Application Markup Language, or XAML as it’s so lovingly known, to cross-platform mobile development. With XAML, application user interfaces can be created declaratively and succinctly.

slider transforms via xaml

To help Xamarin.Forms developers get up to speed, our good friend Charles Petzold took a brief pause from writing his book on Xamarin.Forms to bring you this wonderful guide:

XAML for Xamarin.Forms – Getting Started with Cross-Platform Markup for Mobile Devices.

In it, you’ll find everything you need to work effectively with XAML in Xamarin.Forms. The guide includes 5 action packed parts:

Along with our other great education resources for learning Xamarin.Forms, you now have a wealth of information to help create great cross-platform apps.

June 24, 2014

Webinar Recording: Native Mobile Apps in Xamarin Studio


With an inspired development environment comprised of powerful code completion, support for TestFlight and a dynamic, modern debugger, Xamarin Studio allows developers to build better apps for iOS, Android and Mac.

In this webinar, I give a demo and in-depth look at some of our favorite Xamarin Studio features, including full support for NuGet packages, extensive documentation for the .NET Base Class Libraries (BCL), F# support, and the ability to build native user interfaces with our iOS and Android designers.

Download for Offline Viewing: http://xamarin.wistia.com/medias/z797ghqlps

Webinar slides are available on SlideShare.


Xamarin Studio and NuGet


A new version of Xamarin Studio was released as part of Xamarin 3, and one of its new features and improvements is first class support for NuGet which is now built in and fully integrated.


NuGet is a package management system for .NET that simplifies the process of using third party libraries in your application. It provides access to over 20,000 third party libraries which are available from the main NuGet package gallery.

Microsoft are also embracing NuGet. Microsoft use NuGet as one of the primary ways to release libraries and have their own curated NuGet package feed.

Xamarin is also using NuGet to distribute libraries. Xamarin.Forms, the new library which allows you to build native UIs for iOS, Android and Windows Phone from a shared C# codebase, is available to download from NuGet and install into your application.

Thousands of libraries are available from NuGet, many of these are compatible with Xamarin’s frameworks, that can be used in your iOS, Android, Mac and Windows applications. There are also an increasing number of NuGet packages that contain Portable Class Libraries (PCLs), that are compatible across a range of desktop and mobile frameworks. All of these libraries are now easily available to you from within Xamarin Studio.

Xamarin Studio NuGet Features

  • Search across thousands of third party libraries available as NuGet packages.
  • Quickly add NuGet packages to your application and start using them.
  • Easily update a single package or all packages to their latest versions.
  • Automatically restore packages on opening your solution.
  • Project templates can install NuGet packages when a new project is created.
  • Consume packages from other third party NuGet package sources.
  • Search for NuGet packages from the universal search.
  • Deep integration with Xamarin Studio – integrates with the Solution window, the status bar and the universal search.

Now let us take a look at some of these Xamarin Studio features starting with adding a NuGet package to a project.

Adding a NuGet Package

With your project open in Xamarin Studio, from the Solution window, right click the project and select AddAdd Packages.

Add Packages menu option

This will open the Add Packages dialog showing you a list of NuGet packages available from the main NuGet gallery.

Add Packages Dialog

From this dialog you can search for NuGet packages and quickly add them to your project. Once you have found a package you can install it by simply selecting it and double clicking or by clicking the Add Package button. The dialog will then close and Xamarin Studio will install the NuGet package in the background. As the install proceeds Xamarin Studio’s status bar will be updated with progress messages.



Detailed information on what happened during the install can be seen in the Package Console window.

Xamarin Studio Package Console Window

The Solution window will display a Packages folder which contains all the packages installed in the project.

Package Context Menu in Solution Window

From the Packages folder you can easily update a package to the latest version, or remove it from the project, by right clicking and selecting the appropriate menu item.

Assembly references added to the project by the NuGet package are displayed inside the From Packages folder in the Solution window.

Xamarin Studio From Packages Folder

Restoring NuGet packages

Xamarin Studio will automatically restore any NuGet packages that are missing when a solution is opened. This means you do not need to add NuGet packages to your source control system. Only the packages.config file for each project needs to be added to your source control system. When another developer opens the solution for the first time all the missing NuGet packages will automatically be downloaded and restored by Xamarin Studio.

Xamarin Forms Sample Packages Restored

In the screenshot above the Xamarin.Forms button source code sample, which uses NuGet packages, was opened in Xamarin Studio and the NuGet packages were automatically restored.

Project Templates with NuGet Packages

Project templates now have support for NuGet packages so Xamarin Studio can install NuGet packages when a new project is created. The project templates for Xamarin.Forms takes advantage of this feature and will install NuGet packages when a new Xamarin.Forms project is created.

Learn More

This is the end of our introduction to the NuGet support in Xamarin Studio. If you would like to learn more about Xamarin Studio then here are some more resources.