Unity3d and Parse.com error messages

I’ve used Parse.com quite a bit for iOS development and been very happy with it. Performance and scaling is good, and working with the cloud based service is very straight forward.

I decided to use Parse.com as the back end database solution for my latest Unity3d project. Parse now has an official Unity SDK that you can download from the Unity3d asset store.

Despite all of the benefits of using Parse with Unity there is one glaring problem. Because of the way the Unity implements their WWW class we can’t access response headers containing error information from Parse operations.  So requests sent using the Parse SDK from Unity return responses which can be either successful, failed because of no connection, or failed because of some unknown cause.

Kalekindev has a great blog post addressing this issue. The solution is to create custom cloud code functions on Parse.com and call them instead. The cloud code handles the request and then returns either a success code or an appropriate error message.

Below is my initial cloud code running on Parse (cloud code is in javascript) to handle user signup.

Parse.Cloud.define("SignUp", function(request, response)
{
    var user = new Parse.User();
 
    user.set("username", request.params.username);
    user.set("password", request.params.password);
    user.set("email", request.params.email);
 
    user.signUp(null,
    {
        success: function(user)
        {
            response.success(
                {
                    "success": "Sign up successful."
                });
        },
        error: function(user, error)
        {
            // We must respond with a success in order to access the
            // result of the request inside Unity.
            response.success(
                {
                    "error": "Sign up failed.",
                    "code": error.code,
                    "message": error.message
                });
        }
    });
});

 

And here is the Unity3d C# code snipped that makes the call to the Parse.com cloud code and handles the return code appropriately if there is an error..

 

private IEnumerator CloudSignUp(string sUsername,string sPassword,string sEmail)
{
	var userInfo = new Dictionary
	{
		{"username", sUsername},
		{"password", sPassword},
		{"email", sEmail}


	};
	
	var t = ParseCloud.CallFunctionAsync<Dictionary>("SignUp", userInfo);
	
	while (!t.IsCompleted)
	{
		yield return null;
	}
	
	if (t.IsFaulted)
	{
		var parseException = (ParseException)t.Exception.InnerExceptions[0];
		
		if (parseException.Message.StartsWith("Could not resolve"))
		{
			Debug.Log("Failure: Connection error.");
			objStatus.text="Failure: Connection error.";
			objStatusPanel.SetActive(true);
		}
		else
		{
			// Possible mystery case?
			Debug.Log("Failure: Unknown cause.");
			objStatus.text="Failure: Unknown cause..";
			objStatusPanel.SetActive(true);
		}
	}
	else // Our request is successful but may still have failed server side.
	{
		object code;
		
		if (t.Result.TryGetValue("code", out code))
		{
			// Handle our call specific errors here.
			Debug.Log(string.Format("Failure: Code {0}", code));

			string sCode = string.Format("{0}", code);
	
			if (sCode.Equals("125")) {

				objStatus.text="Email is invalid";
				objStatusPanel.SetActive(true);

				Debug.Log("bad email");
			}

			 else if (sCode.Equals("202")) {
				
				objStatus.text="Username is already in use.";
				objStatusPanel.SetActive(true);
				
				Debug.Log("bad username");
			}

			else if (sCode.Equals("203")) {
				
				objStatus.text="Email is already in use.";
				objStatusPanel.SetActive(true);
				
				Debug.Log("bad username");
			}

			else {

				objStatus.text=string.Format("Failure: Code {0}", code);
				objStatusPanel.SetActive(true);
	
			}


		}
		else
		{
			Debug.Log("Success!");
		}
	}
}

 

This approach can be used for all Parse.com functions called from Unity and gives us a robust way to handle exceptions and errors.

Augmented Reality on iOS

Durovis Dive

I’ve been working on an AR (augmented reality) application for iOS and thought I would share some of the available software libraries and devices for iOS.

Hardware

Although an iPhone is not as ‘hands free’ as a dedicated AR device (Moverio, Vuzix, or the Meta SpaceGlasses) there are interesting hardware solutions to use your iPhone or Android smart phone as a AR client…

Durovis Dive

Durovis Dive

The Durovis Dive works with any Android or iOS smartphone featuring a gyroscope and an accelerometer and a display not larger than 5 inches. You just insert your smartphone, start the application and adjust the lenses to your eyes.

FOV2GO

FOV2GO

You can construct your own FOV2GO Model D Viewer – for the iPhone 4/4S, the Samsung Galaxy Note, or most Android smart phones – out of foam board and a couple of plastic lenses. Just download the instructions and the appropriate template.

Software

Source for my initial research and a great resource at Augmented Reality SDK Comparison

 

Open Source and/or Free

Argon
iOs – augmented reality from Georgi Tech – appears to be open source but I can’t find the code available for download – based on KHARMA – a KML/HTML Augmented Reality Mobile Architecture

iPhone ARKit
iOS – iPhone ARKit is a small set of class that can give you augmented reality in any iPhone application.

iPhone Augmented Reality Toolkit
This version of the iPhone ARKit is a forked version of the ARKit started on GitHub by Zac White.

mixare – Open Source Augmented Reality Engine
iOS & Android – It works as a completely autonomous application and is available as well for the development of own implementations.

PRAugmentedReality
open source – Augmented Reality Framework for iOS

Vuforia
(from Qualcomm)
iOS, Android, and Unity 3D
Very powerful tracker based AR SDK – free for commercial development

 

Proprietary and/or Paid

ARPA
iOS & Android

ARToolKit
iOS & Android – a very powerful Lib with a lot of work being done with it – has an open source version (but not on mobile devices)

Catchoom
iOS & Android

Metaio
iOS & Android (includes Junaio) – lots of products, including content creation and a cloud offering

Robocortex

String
Comes in vanilla OpenGL and Unity flavours. Add AR to any iOS project, regardless of 3D engine.

Wikitude
iOS, Android and BlackBerry 10 – both tools for client and creation – also has an AR browser app – very popular with a lot of dev shops using it

Xloudia
cloud based AR recognition and tracking

 

Roll your Own

Augmented Reality iOS Tutorial: Location Based

Augmented Reality iOS Tutorial: Marker Tracking

Results of Hackathon

angle hack austin

preparing for demos

This weekend I won 2nd place at the AppHack Austin with ShareMesh – an iOS based encrypted peer to peer messaging app that does not require an internet connection to operate. The app used the new iOS 7 features iBeacon and Multipeer Connectivity to handle discovery and communication between devices.

I had a great time and there were a lot of interesting projects and very talented people working on them (see a list at hackathon.io).

The Capital Factory facilities are world class and the folks from AngelHack and our sponsors were great hosts. Looking forward for the chance to go to the Spring 2014 HACKcelerator program in San Francisco.

hackathon_nov_2014_codingonsaturday hackathon_nov_2013_presentation

AngelHack Austin Fall 2013

I’m attending the AngelHack Mobile App Hackathon this weekend in Austin, TX.

It is hosted at Capital Factory – a start-up incubator with 50,000 square feet of amazing work space.

I get about 24 hours to turn an idea into an app, some of the ones I’m looking at are…

  • ghost net – an encrypted peer to peer communications layer that lets users exchange messages/pictures between smartphones without using the internet or any other means detectable by totalitarian governments (Egypt, or NSA)
  • Arduino Bridge – software to link an iPhone as a sensor platform the the DIY chips and maker projects that use the Adruino
  • iDead – live action zombie game based on location of your iPhone
  • Crowd video processing – upload pictures of an event from all participants – stitch together into single browse-able panoramic / 3d scene
  • video recognition – use open source video processing software to train your iPhone to recognize objects that walk past the camera (trigger an alert when ‘lady in red’ walks by)
  • iPhone/robotic integration -use sphero or romo to link with an iPhone and do interesting things (room mapping, object manipulation, etc) and/or games

iOS Projects We’re Working On

Here are some of our recent iOS projects…

* YourTeacher.com – We continue to be the iOS app development arm for yourteacher.com. They have over thirty titles in the Apple App store – majority of which have 4.5+ average ratings with literally hundreds of thousands of downloads per app.

Algebra, ASVAB, or Math are some examples of the work we’ve done for them.

* Just Picture It – created in partnership with the Mason Software Company. It evolves a mobile photo sharing into a word game with friends and family. In a turn-based game you can play in single and multiplayer mode.

Just Picture It uses the Parse.com api extensively for user authentication, push notifications, and storage of games and messages.

Rich Text Format (RTF) documents from your web2py application

We needed to generate Microsoft Word .doc files from a web application based on web2py.  Creating a .doc file from scratch from python is no small task, but luckily for us rtf (Rich Text Format) files can be opened natively by Word and cover everything we needed.

Web2py includes the pyrtf library. Pyrtf is a set of python classes that make it possible to produce RTF documents from python programs. The library has no external dependencies and has proven reliable and fast.

The code snippet below is in a web2py function, it imports the library, initializes it and then creates a simple rtf doc.

After adding the line ‘Certified Staff Evaluation’ the function returns the newly created doc file. It is possible to create tables and include images – documentation for the library and example rtf generation files can be found at PyRTF. (note that web2py uses a slightly older version of pyrtf – you can see docs for it here.

from gluon.contrib.pyrtf import *

doc     = Document()
ss      = doc.StyleSheet
section = Section()
doc.Sections.append( section )

p = Paragraph( ss.ParagraphStyles.Heading1 )
p.append( 'Certified Staff Evaluation' )
section.append( p )
return doc

Using Parse to login via Facebook and retrieve Profile and Friends

I’m using parse.com to handle user authentication, either via Facebook or custom user type with email and password.

If a user signs up via Facebook we want to request access to their profile and friend list and use that information to find FB friends who are already playing our game (Just Picture It).

This example doesn’t include a lot of the prerequisite steps to get your parse app working with Facebook – see the parse.com docs for more details on that.

An example of an initial call to parse to login to Facebook with a specific set of permissions.

NSArray *permissionsArray = [NSArray arrayWithObjects:@"user_about_me",
@"user_relationships",@"user_birthday",@"user_location",
@"offline_access", @"email", @"publish_stream", nil];

[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {

if (!user) {
   NSLog(@"Uh oh. The user cancelled the Facebook login.");

   [self doFacebookUserHasCanceled];

   } else {

     [self performSelector:@selector(doFaceBookUserHasLoggedIn) withObject:nil afterDelay:0.1];
     }
}];

A successful login and permission request approval by the user to Facebook sends us to the function doFaceBookUserHasLoggedIn.

NSString *requestPath = @"me/?fields=name,location,gender,birthday,relationship_status,picture,email,id";

PF_FBRequest *request = [[PF_FBRequest alloc] initWithSession:[PFFacebookUtils session] graphPath:requestPath];

[request startWithCompletionHandler:^(PF_FBRequestConnection *connection, id result, NSError *error) {
    if (!error) {
       NSDictionary *userData = (NSDictionary *)result; // The result is a dictionary

       NSString *name = [userData objectForKey:@"name"];

       NSString *email = [userData objectForKey:@"email"];

       NSString *sID = [userData objectForKey:@"id"];

       // get the FB user's profile image
       NSDictionary *dicFacebookPicture = [userData objectForKey:@"picture"];   
       NSDictionary *dicFacebookData = [dicFacebookPicture objectForKey:@"data"];       
       NSString *sUrlPic= [dicFacebookData objectForKey:@"url"];
       UIImage* imgProfile = [UIImage imageWithData:
                                [NSData dataWithContentsOfURL:
                                 [NSURL URLWithString: sUrlPic]]];

       //do something interesting with this data...

       //...

       // now request FB friend list
       PF_FBRequest *request = [[PF_FBRequest alloc] initWithSession:[PFFacebookUtils session] graphPath:@"me/friends"];

       [request startWithCompletionHandler:^(PF_FBRequestConnection *connection, id result, NSError *error) {
          if (!error) {
             NSArray *data = [result objectForKey:@"data"];

             if (data) {
                //we now have an array of NSDictionary entries contating friend data
                for (NSMutableDictionary *friendData in data) {
                    // do something interesting with the friend data...

                    }
                }

             }
          }];
   }
}];