F# iOS Program: 39 lines of code

Xamarin loves F#!

fsharp_too

Of course you can use F# to program iOS and Android applications using Xamarin and Visual Studio!

namespace Simple

open System
open MonoTouch.UIKit
open MonoTouch.Foundation
open System.Drawing

type ContentView ( color : UIColor ) as self = 
    inherit UIView ()
    do 
        self.BackgroundColor < - color

type SimpleController ( ) =
    inherit UIViewController ()

    override this.ViewDidLoad () = 
        this.View <- new ContentView(UIColor.Blue)

[<Register ("AppDelegate")>]
type AppDelegate () =
    inherit UIApplicationDelegate ()

    let window = new UIWindow (UIScreen.MainScreen.Bounds)

    // This method is invoked when the application is ready to run.
    override this.FinishedLaunching (app, options) =
        let viewController = new SimpleController()
        viewController.Title <- "F# Rocks"

        let navController = new UINavigationController(viewController)
        window.RootViewController <- navController
        window.MakeKeyAndVisible ()
        true

module Main =
    [<EntryPoint>]
    let main args =
        UIApplication.Main (args, null, "AppDelegate")
        0

Screen Shot 2013-11-13 at 11.46.50 AM

Cheatsheet for iOS 7 Design Sizes

Helpful: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Natively Recognize Barcodes/QR Codes in iOS 7 with Xamarin.iOS

There have been great barcode-reading libraries available for Xamarin for some time, but iOS 7 has built-in barcode-recognition support.

There’s only one tricky bit: you have to tell the AVCaptureMetadataOutput what types of barcodes you’re interested in after you’ve added it to the AVCaptureSession. (I suppose what happens behind the scene is that the AVCaptureSession registers with the AVCaptureMetadataOutput the various types of barcodes it could recognize.)

UPDATE: This also works for realtime face detection! s/AVMetadataMachineReadableCodeObject/AVMetadataFaceObject/ and set AVMetadataObject.TypeFace!

Here’s a complete program in Xamarin.iOS that recognizes QR and standard Ean13 barcodes:

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.CoreGraphics;
using MonoTouch.AVFoundation;
using MonoTouch.CoreFoundation;

namespace SingleFileSolution
{
	public class ContentView : UIView
	{
		AVCaptureVideoPreviewLayer layer; 

		public ContentView(UIColor fillColor, AVCaptureVideoPreviewLayer layer, MyMetadataOutputDelegate metadataSource)
		{
			BackgroundColor = fillColor;


			this.layer = layer;
			layer.MasksToBounds = true;
			layer.VideoGravity = AVCaptureVideoPreviewLayer.GravityResizeAspectFill;

			Frame = UIScreen.MainScreen.Bounds;
			layer.Frame = Frame;
			Layer.AddSublayer(layer);

			var label = new UILabel(new RectangleF(40, 80, UIScreen.MainScreen.Bounds.Width - 80, 80));
			AddSubview(label);

			metadataSource.MetadataFound += (s, e) => label.Text = e.StringValue;

		}

		public override void LayoutSubviews()
		{
			base.LayoutSubviews();
			layer.Frame = Bounds;
		}
	}

	public class MyMetadataOutputDelegate : AVCaptureMetadataOutputObjectsDelegate
	{
		public override void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection)
		{
			foreach(var m in metadataObjects)
			{
				if(m is AVMetadataMachineReadableCodeObject)
				{
					MetadataFound(this, m as AVMetadataMachineReadableCodeObject);
				}
			}
		}

		public event EventHandler<AVMetadataMachineReadableCodeObject> MetadataFound = delegate {};
	}

	public class SimpleViewController : UIViewController
	{
		AVCaptureSession session;
		AVCaptureMetadataOutput metadataOutput;

		public SimpleViewController() : base()
		{
		}

		public override void DidReceiveMemoryWarning()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning();
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			
			session = new AVCaptureSession();
			var camera = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
			var input = AVCaptureDeviceInput.FromDevice(camera);
			session.AddInput(input);

			//Add the metadata output channel
			metadataOutput = new AVCaptureMetadataOutput();
			var metadataDelegate = new MyMetadataOutputDelegate();
			metadataOutput.SetDelegate(metadataDelegate, DispatchQueue.MainQueue);
			session.AddOutput(metadataOutput);
			//Confusing! *After* adding to session, tell output what to recognize...
			foreach(var t in metadataOutput.AvailableMetadataObjectTypes)
			{
				Console.WriteLine(t);
			}
			metadataOutput.MetadataObjectTypes = new NSString[] {
				AVMetadataObject.TypeQRCode,
				AVMetadataObject.TypeEAN13Code
			};

			var previewLayer = new AVCaptureVideoPreviewLayer(session);
			var view = new ContentView(UIColor.Blue, previewLayer, metadataDelegate);

			session.StartRunning();
		
			this.View = view;
		}
	}

	[Register("AppDelegate")]
	public  class AppDelegate : UIApplicationDelegate
	{
		UIWindow window;
		SimpleViewController viewController;

		public override bool FinishedLaunching(UIApplication app, NSDictionary options)
		{
			window = new UIWindow(UIScreen.MainScreen.Bounds);

			viewController = new SimpleViewController();
			window.RootViewController = viewController;

			window.MakeKeyAndVisible();
			
			return true;
		}
	}

	public class Application
	{
		static void Main(string[] args)
		{
			UIApplication.Main(args, null, "AppDelegate");
		}
	}
}

Helpful list of Apple-supplied 3D buildings, turn-by-turn, etc.

My Favorite iOS 7 APIs Part 3 : CoreMotion (iPhone 5S only)

The new M7 coprocessor in the iPhone 5S makes pedometer apps trivial:

    if(CMStepCounter.IsStepCountingAvailable)
    {
        var counter = new CMStepCounter();
        //Last 8 hours
	counter.QueryStepCount(NSDate.FromTimeIntervalSinceNow(-8 * 60 * 60), NSDate.Now, NSOperationQueue.CurrentQueue, StepQueryHandler);
    }

    void StepQueryHandler(int nssteps, NSError error)
    {
        Console.WriteLine(nssteps);
    }

3D Buildings Not Showing in Your iOS App?

I totally forgot a frustrating detail about showing 3D buildings in iOS 7 : it doesn’t work in the simulator! You have to use a hardware device!

My Favorite iOS 7 APIs: Multipeer Connectivity

Multipeer Connectivity allows you to discover and share data with other iOS devices within Bluetooth radio range or on the same WiFi subnet. It is much easier to use than Bonjour.

I wrote a simple MPC chat program in Xamarin.iOS.

There’s necessarily a few hundred lines of code, but 90% of it is just the scaffolding necessary to support a four-view application. The actual discovery and communication is done with just a handful of code.

There are two phases for Multipeer Connectivity: Discovery and the Session phase. During the Discovery phase, one device acts as a coordinator or browser, and many devices advertise their interest in connecting. Devices advertise their interest in sharing a protocol defined by a string.

I created a base class DiscoveryViewController : UIViewController for both the advertising and browsing:

//Base class for browser and advertiser view controllers
public class DiscoveryViewController : UIViewController
{
	public MCPeerID PeerID { get; private set; }

	public MCSession Session { get; private set; }

	protected const string SERVICE_STRING = "xam-chat";

	public DiscoveryViewController(string peerID) : base()
	{
		PeerID = new MCPeerID(peerID);
	}

	public override void ViewDidLoad()
	{
		base.ViewDidLoad();

		Session = new MCSession(PeerID);
		Session.Delegate = new DiscoverySessionDelegate(this);
	}

	public void Status(string str)
	{
		StatusChanged(this, new TArgs<string>(str));
	}

	public event EventHandler<targs <string>> StatusChanged;
}

This base class holds a PeerID (essentially, the nickname for the device in the chat), an MCSession (the actual connection), and a SERVICE_STRING that specifies what type of MPC session I support (“xam-chat”). Additionally, it exposes an event StatusChanged (which is subscribed to by a UILabel in the DiscoveryView class (not shown, because it’s trivial).

Events relating to the MCSession are handled by ChatSessionDelegate, but those occur after discovery, so putting that aside for now, let’s look at how simple are the AdvertiserController and BrowserController subtypes of DiscoveryViewController:

public class AdvertiserController : DiscoveryViewController
{
	MCNearbyServiceAdvertiser advertiser;

	public AdvertiserController(string peerID) : base(peerID)
	{
	}

	public override void DidReceiveMemoryWarning()
	{
		// Releases the view if it doesn't have a superview.
		base.DidReceiveMemoryWarning();

		// Release any cached data, images, etc that aren't in use.
	}

	public override void ViewDidLoad()
	{
		base.ViewDidLoad();

		View = new DiscoveryView("Advertiser", this);
		var emptyDict = new NSDictionary();
		Status("Starting advertising...");

		advertiser = new MCNearbyServiceAdvertiser(PeerID, emptyDict, SERVICE_STRING);
		advertiser.Delegate = new MyNearbyAdvertiserDelegate(this);
		advertiser.StartAdvertisingPeer();
	}
}

class MyNearbyAdvertiserDelegate : MCNearbyServiceAdvertiserDelegate
{
	AdvertiserController parent;

	public MyNearbyAdvertiserDelegate(AdvertiserController parent)
	{
		this.parent = parent;
	}

	public override void DidReceiveInvitationFromPeer(MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, MCNearbyServiceAdvertiserInvitationHandler invitationHandler)
	{
		parent.Status("Received Invite");
		invitationHandler(true, parent.Session);
	}
}

public class BrowserController : DiscoveryViewController
{
	MCNearbyServiceBrowser browser;

	public BrowserController(string peerID) : base(peerID)
	{
	}

	public override void DidReceiveMemoryWarning()
	{
		// Releases the view if it doesn't have a superview.
		base.DidReceiveMemoryWarning();

		// Release any cached data, images, etc that aren't in use.
	}

	public override void ViewDidLoad()
	{
		base.ViewDidLoad();

		View = new DiscoveryView("Browser", this);

		browser = new MCNearbyServiceBrowser(PeerID, SERVICE_STRING);
		browser.Delegate = new MyBrowserDelegate(this);

		Status("Starting browsing...");
		browser.StartBrowsingForPeers();
	}

	class MyBrowserDelegate : MCNearbyServiceBrowserDelegate
	{
		BrowserController parent;
		NSData context;

		public MyBrowserDelegate(BrowserController parent)
		{
			this.parent = parent;
			context = new NSData();
		}

		public override void FoundPeer(MCNearbyServiceBrowser browser, MCPeerID peerID, NSDictionary info)
		{
			parent.Status("Found peer " + peerID.DisplayName);
			browser.InvitePeer(peerID, parent.Session, context, 60);
		}

		public override void LostPeer(MCNearbyServiceBrowser browser, MCPeerID peerID)
		{
			parent.Status("Lost peer " + peerID.DisplayName);
		}

		public override void DidNotStartBrowsingForPeers(MCNearbyServiceBrowser browser, NSError error)
		{
			parent.Status("DidNotStartBrowingForPeers " + error.Description);
		}
	}
}

Quite a few lines, but very straightforward: the advertiser uses the iOS class MCNearbyServiceAdvertiser and the browser uses the class MCNearbyServiceBrowser. The browser’s delegate responds to discovery by calling MCNearbyServiceBrowser.InvitePeer and the advertiser’s delegate responds to an invitation by passing true to the invitationHandler.

The Chat Session

When the invitation is accepted, it’s time for the ChatSessionDelegate to take over:

public class ChatSessionDelegate : MCSessionDelegate
{
	public DiscoveryViewController Parent{ get; protected set; }

	public ChatViewController ChatController
	{
		get; 
		set;
	}

	public ChatSessionDelegate(DiscoveryViewController parent)
	{
		Parent = parent;
	}

	public override void DidChangeState(MCSession session, MCPeerID peerID, MCSessionState state)
	{
		switch(state)
		{
		case MCSessionState.Connected:
			Console.WriteLine("Connected to " + peerID.DisplayName);
			InvokeOnMainThread(() => Parent.NavigationController.PushViewController(new ChatViewController(Parent.Session, Parent.PeerID, peerID, this), true));
			break;
		case MCSessionState.Connecting:
			Console.WriteLine("Connecting to " + peerID.DisplayName);
			break;
		case MCSessionState.NotConnected:
			Console.WriteLine("No longer connected to " + peerID.DisplayName);
			break;
		default:
			throw new ArgumentOutOfRangeException();
		}
	}

	public override void DidReceiveData(MCSession session, MonoTouch.Foundation.NSData data, MCPeerID peerID)
	{

		if(ChatController != null)
		{
			InvokeOnMainThread(() => ChatController.Message(String.Format("{0} : {1}", peerID.DisplayName, data.ToString())));
		}
	}

	public override void DidStartReceivingResource(MCSession session, string resourceName, MCPeerID fromPeer, MonoTouch.Foundation.NSProgress progress)
	{
		InvokeOnMainThread(() => new UIAlertView("Msg", "DidStartReceivingResource()", null, "OK", null).Show());

	}

	public override void DidFinishReceivingResource(MCSession session, string resourceName, MCPeerID formPeer, MonoTouch.Foundation.NSUrl localUrl, out MonoTouch.Foundation.NSError error)
	{
		InvokeOnMainThread(() => new UIAlertView("Msg", "DidFinishReceivingResource()", null, "OK", null).Show());
		error = null;

	}

	public override void DidReceiveStream(MCSession session, MonoTouch.Foundation.NSInputStream stream, string streamName, MCPeerID peerID)
	{
		InvokeOnMainThread(() => new UIAlertView("Msg", "DidReceiveStream()", null, "OK", null).Show());

	}
}

Again, this is mostly scaffolding, but be sure to note that it expects to be called on a background thread and uses InvokeOnMainThread to manipulate the UI. It also relies on the ChatViewController:

public class ChatViewController : UIViewController, IMessager
{
	protected MCSession Session { get; private set; }

	protected MCPeerID Me { get; private set; }

	protected MCPeerID Them { get; private set; }

	ChatView cv;

	public ChatViewController(MCSession session, MCPeerID me, MCPeerID them, ChatSessionDelegate delObj) : base()
	{
		this.Session = session;
		this.Me = me;
		this.Them = them;

		delObj.ChatController = this;
	}

	public override void DidReceiveMemoryWarning()
	{
		// Releases the view if it doesn't have a superview.
		base.DidReceiveMemoryWarning();

		// Release any cached data, images, etc that aren't in use.
	}

	public override void ViewDidLoad()
	{
		base.ViewDidLoad();

		cv = new ChatView(this);
		View = cv;

		cv.SendRequest += (s, e) => {
			var msg = e.Value;
			var peers = Session.ConnectedPeers;
			NSError error = null;
			Session.SendData(NSData.FromString(msg), peers, MCSessionSendDataMode.Reliable, out error);
			if(error != null)
			{
				new UIAlertView("Error", error.ToString(), null, "OK", null).Show();
			}
		};
	}

	public void Message(string str)
	{
		MessageReceived(this, new TArgs<string>(str));
	}

	public event EventHandler<targs <string>> MessageReceived = delegate {};
}

Again, it’s the simplicity that stands out: Session.SendData is used to transmit a string. The SendRequest event is wired to a UITextField and the MessageReceived event is wired to a UILabel:

public class ChatView : UIView
{
	readonly UITextField message;
	readonly UIButton sendButton;
	readonly UILabel incoming;

	public ChatView(IMessager msgr)
	{
		BackgroundColor = UIColor.White;

		message = new UITextField(new RectangleF(10, 54, 100, 44)) {
			Placeholder = "Message"
		};
		AddSubview(message);

		sendButton = new UIButton(UIButtonType.System) {
			Frame = new RectangleF(220, 54, 50, 44)
		};
		sendButton.SetTitle("Send", UIControlState.Normal);
		AddSubview(sendButton);

		incoming = new UILabel(new RectangleF(10, 114, 100, 44));
		AddSubview(incoming);

		sendButton.TouchUpInside += (sender, e) => SendRequest(this, new TArgs<string>(message.Text));
		msgr.MessageReceived += (s, e) => incoming.Text = e.Value;
	}

	public event EventHandler<targs <string>> SendRequest = delegate {};
}

The ChatViewController.Message method is called by the ChatSessionDelegate.DidReceiveData method.

And that’s really all there is to it.

Dynamic Type in iOS 7: Not Quite as “Dynamic” as You Might Think

One of the nice features in iOS 7 for old fogeys such as myself is that the user can use the general Settings to increase and decrease the fonts used in apps. This is called “Dynamic Type.” Judging by developer forums, I’m not the only one who thought that this was something that was built in to the various widgets. It’s not. To do this in your own app, you have to respond to the ContentSizeCategoryChanged notification and invalidate the layout in any widgets you want to have change size. In Xamarin.iOS, the code looks like this:

public class ContentView : UIView
{
    public ContentView()
    {
       var txt = new UITextView(UIScreen.MainScreen.Bounds);
       txt.Text = "Lorem ipsum dolor ...";
       ResetDynamicType();
       //Respond to notification of change
        UIApplication.Notifications.ObserveContentSizeCategoryChanged((s,e) => {
          ResetDynamicType();
        });
        AddSubview(txt);
    }
    public void ResetDynamicType()
    {
        txt.Font = UIFont.PreferredFontForTextStyle(UIFontTextStyle.Body);
    }
}

The crucial point being that you have a ResetDynamicType method (or whatever you want to call it) that you call both at initialization and then again every time you get notified of a request to change font size (if you want, you can read the new size from the e in the lambda). So “Dynamic Type” isn’t really anything special in terms of display: it’s still up to the application developer to have a function that’s called. What is dynamic is the value returned by UIFont.PreferredFontForTextStyle, which varies based on the user’s Settings.

Xamarin Code for iBeacons

Did I mention how easy it is to track an iBeacon using Xamarin?

locationManager = new CLLocationManager();
var beaconId = new NSUuid("E437C1AF-36CE-4BBC-BBE2-6CE802977C46");
var beaconRegion = new CLBeaconRegion(beaconId, "My Beacon");
locationManager.RegionEntered += (s, e) => {
    if(e.Region.Identifier == "My Beacon")
    {
        Console.WriteLine("Found My Beacon");
        //Fire up ranging
        locationManager.StartRangingBeacons(beaconRegion);
        locationManager.DidRangeBeacons += (lm, rangeEvents) => {
            switch(rangeEvents.Beacons[0].Proximity)
            {
            case CLProximity.Far: 
                Console.WriteLine("You're getting colder!");
                break;
            case CLProximity.Near:
                Console.WriteLine("You're getting warmer!");
                break;
            case CLProximity.Immediate:
                Console.WriteLine("You're red hot!");
                break;
            case CLProximity.Unknown: 
                Console.WriteLine("I can't tell");
                break;
            default:
                throw new ArgumentOutOfRangeException();
            }
        };
    }
};
locationManager.StartMonitoring(beaconRegion);
//Create a beacon
var peripheralManager = new CBPeripheralManager(new MyPeripheralDelegate(), DispatchQueue.DefaultGlobalQueue, new NSDictionary());
var beaconOptions = beaconRegion.GetPeripheralData(null);
peripheralManager.StartAdvertising(beaconOptions);

My Favorite iOS 7 APIs Part 1: iBeacons and Multipeer Connectivity

Since Xamarin provides full native capabilities, developers don’t need to wait for us to exploit iOS 7′s awesome new APIs, such as:

  • iBeacon: This, to my mind, is the stealth API of the release. An iBeacon is a Bluetooth device (just iOS devices for now, but Apple says they’ll release a Bluetooth profile for h/w manufacturers) that broadcasts a UUID (the UUID is intended to be shared between many devices, e.g., a store-chain will have a UUID and all their stores will broadcast it: new store’s geofence works instantly). The UUID travels up to Apple and apps that monitor for that UUID get alerted when they enter a geofence around the beacon. Within the beacon’s region, BT, not GPS, is used to indicate proximity. Pair that with…

  • Multipeer Connectivity: Ad Hoc messaging and data with none of the hassle. Broadcast a protocol string (“com.MyCompany.MyApp”) and everyone in BT range or on the same WiFi network advertising their interest in that protocol string gets an alert and, boom!, you’ve got Birds of a Feather. (Whoever writes the “Fetish Friend Finder” app using iBeacon and MPC is going to retire early. Of course, there are only 2^122 GUIDs, so you couldn’t track every kink.) (UPDATE: A sample chat app I wrote )

iBeacons can be combined to create many actionable zones within a physical location:

Here’s some Xamarin code

div>