Archive

Posts Tagged ‘iPhone’

MonoTouch: Simple Web Server

August 18, 2010 Leave a comment

A web server can be a very flexible solution to transferring data from your application. MonoTouch makes it extremely easy to add a web server to your iPhone/iPad application by using the HttpListener class. You can actually implement one with just two methods.

Now this is a very simple example that will just serve up some HTML but you can start from it and extend it to whatever your needs may be. Download the solution file here.

You’ll need to declare two member variables:

private HttpListener listener;
private bool listenerRunning = false;

I used a button click event to both start and stop the server:

partial void startOrStopServer (UIButton sender)
{
	if (!listenerRunning) {
		listener = new HttpListener();
		//Add generic prefix using port 8080
		listener.Prefixes.Add("http://*:8080/");
		
		//Start the server
		listener.Start();
		txtInfo.Text += "Server Started\n";
		btnStart.SetTitle("Stop Server", UIControlState.Normal);
	
		//Begin listening for requests asynchronously
		listener.BeginGetContext(new AsyncCallback(HandleRequest), listener);
	} else {
		//Close the server
		listener.Close();
		listener = null;
		txtInfo.Text += "Server Stoped\n";
		btnStart.SetTitle("Start Server", UIControlState.Normal);
	}
	
	listenerRunning = !listenerRunning;
} 

Request handler method:

private void HandleRequest(IAsyncResult result) {
	if (!listenerRunning) return;
	
	//Get the listener context
	HttpListenerContext context = listener.EndGetContext(result);
	//Start listening for the next request
	listener.BeginGetContext(new AsyncCallback(HandleRequest), listener);
	
	//Update status on the UI thread
	InvokeOnMainThread( delegate {
		txtInfo.Text += "Received request from: " + context.Request.UserHostAddress + "\n";
	});
	
	//Here you can create any response that you want. You can serve text or a file or whatever else you need.
	string response = "<html><head><title>Sample Response</title></head><body>Response from mtouchwebserver.</body></html>";
	byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
	
	//Set some response information
	context.Response.ContentType = "text/html";
	context.Response.StatusCode = (int)HttpStatusCode.OK;
	context.Response.ContentLength64 = responseBytes.Length;
	
	//Write the response.
	context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
	context.Response.OutputStream.Close();
}

You can run the example solution in the iPhone simulator, start the server, then open a browser and go to http://localhost:8080 to see the results.

Categories: C#, iPhone, MonoTouch Tags: , , ,

Drawing with MonoTouch.

October 2, 2009 6 comments

Here’s a simple example on using Quartz 2D with MonoTouch.

First you need to create a CGBitmapContext object:

int width = 100;
int height = 100;
CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, width, height, 8, 4 * width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst);

Then set some color settings such as the fill and stroke colors:

CGColor red = new CGColor(1f, 0f, 0f, 1f);
CGColor black = new CGColor(0f, 0f, 0f, 1f);
ctx.SetFillColorWithColor(red);
ctx.SetStrokeColorWithColor(black);

Now you can start drawing:

//Draw an ellipse
ctx.FillEllipseInRect(new RectangleF(0, 0, width, height));

//Draw a rectangle inside the ellipse
ctx.SetFillColorWithColor(black);
ctx.FillRect(new RectangleF(width / 4, height / 4, width / 2, height / 2));

Draw some text:

ctx.SetFillColorWithColor(red);
ctx.SelectFont("Arial", 12f, CGTextEncoding.MacRoman);
ctx.ShowTextAtPoint(width / 2, height / 2, "Hi!");

Once you are done drawing you can save your image or display it in a UIImageView using the ToImage() method:

//Show the image in a UIImageView:
myUIImageView.Image = UIImage.FromImage(ctx.ToImage());

//Save your image to file:
UIImage toSave = UIImage.FromImage(ctx.ToImage());
NSError err = new NSError();
toSave.AsJPEG().Save(Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.Personal), "myimage.jpg"), true, out err);

That should get you on your way to drawing some basic images with MonoTouch. I’ll cover some more advanced techniques in my next post.

Categories: iPhone, MonoTouch Tags: , ,
Follow

Get every new post delivered to your Inbox.