NSUrlConnection MonoTouch Helper class

Posted by ESCOZ on Wednesday, November 24, 2010

After rewriting a few apps to use NSUrlConnection, I came up with a useful wrapper class to handle connections, which I thought other people might find useful. The class not only transforms the classic delegate pattern into Action parameters, but also takes care of displaying the iPhone spinning wheel and keeps track of connections, so they can be all killed at once (useful when the user moves to a different tab in an app, for example).

You can find the class here.

To use this class, first add to it to your project, and change the code that handles authorization to fit your requirements (around line 90). In my case, the class is set to accept SSL certificates from the server, as well as use HTTP Auth using values from a singleton object in Application.Account. Change this as you see fit.

Finally, to make a call to the server, you need to first create a NSUrlRequest object with the proper parameters, and then create the custom request, like the following:

var req = new NSMutableUrlRequest(new NSUrl("http://www.google.com/"),
NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, 20);
req["Accept-Encoding"] = "gzip";

new EscozUrlConnection("connectionName", req,
        (string result)=>{ new UIAlertView("Completed!", result, null, "OK").Show(); }, //parse xml or json here
        ()=>{ new UIAlertView("Failure!", null, null, "OK").Show(); }
);

The “connectionName” is used to keep track of the connection, so it can be killed later directly, using EscozUrlConnection.KillConnection(“connectionName”). You can also kill all connections using EscozUrlConnection.KillAllConnections().

I hope this is helpful to somebody.