Skip to content

How To Build An Cocos2d iOS App Communicating With A RESTful API – Intro

I want to start a series on a topic that was not too hard to get together but resources were quite distributed and some rocks were in my way as an Objective-C newbie.

I want to show how you can render JSON information retrieved via REST web services. The following picture Combat Screen shows an example.

CombatUILayer

Combat Screen

Yes, it doesn’t look perfect at all but I don’t want to show my design skills. What you see in the pic is pretty obvious I hope. In its final version it should show a combat screen allowing an offensive Monster to attack a dungeon that is going to be defended from the right hand side Monster. On the left side are the offenders attributes and on the right side are the defenders attributes. All information of that monsters reside on the web app that we can request via our Web API. How to build up the Web API with Play! I will discuss in another post – for now just let’s assume there is something like http://localhost/playerId/monsters/monster/id. We can use HTTP GET to obtain information via that URL.

I think it makes sense to split this how-to into smaller pieces freely following the divide and conquer principle. The figure below shows the whole picture I want to explain.

ClassViewBlocks.040

Class Overview

  1. When invoked/clicked by the user the CombatUILayer : CCLayer component initiates two MonsterView : CCNode classes that should be rendered – one for the attacking monster in view and one for the defending
  2. First, the MonsterController : NSObject creates the MonsterView object requested by the CombatUILayer
  3. Second, the BaseMonster : NSObject class invokes an asynchronous HTTP request to our Web API given a Block code that will be invoked when the HTTP request returns (either successful or not)
  4. The HttpRequest class that defines all need methods to implement the needed HTTP protocol. It is given the Block code we defined in the BaseMonster class.
  5. The defined Block code being invoked when the asynchronous HTTP request returned will update the CombatUILayer to actually draw the retrieved information.

The following posts will detail code of the View, Model and Controller part of the solution from an iOS perspective.