Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Trabla: Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Solving:

In this tutorial we will implement simple wrapper for www calls and processing it.
Calling of API will be so easy, e.g.

  api.xgSignIn (this, lvLogin, lvPassword);

where this - object which implements handler method 

Naming convention:
I will use prefix X<ClassName>  e.g. XServiceModel.
I will use prefix XI<InterfaceName> e.g. XIServiceCallbackHandler
I will use prefix xg<MethodName> e.g.  void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

1. Create C# script   XServiceEventModel.cs  with following code:

using UnityEngine;
using System.Collections;

public class XServiceEventModel {

    public int id { get; set; }
    public string data{ get; set; }
    public string error{ get; set; }

}



2. Create C# script XIServiceCallbackHandler.cs - interface with only one method.
Any view should implement it in order to process WWW callbacks. copy following code:

using UnityEngine;
using System.Collections;

public interface XIServiceCallbackHandler {

    void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

}


3. Create C# script XApiServic.cs - this class is a wrapper of your web-server api.
Use following code:


using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;

public class XApiService : MonoBehaviour {


  

    private const string API_URL     = "http://mysite.com/api/mygame1";
    private const string APP_TOKEN    = "2ba908bb34566e1ba91a5e570d0287";

    #region Event Types


    public const int EVENT_SIGN_IN_SUCCESS     = 10;
    public const int EVENT_SIGN_IN_FAILED     = 11;

    public const int EVENT_RESULTS_SAVE_SUCCESS = 20;
    public const int EVENT_RESULTS_SAVE_FAILED = 21;

  

    #endregion

   
    public void xgSignIn( XIServiceCallbackHandler callbackHandler, string login, string password ){

        string url = API_URL + string.Format ( "/signin?app={0}&login={1}&password={2}", APP_TOKEN, login, password );

        Dictionary<string, string> headers = new Dictionary<string, string> ();
        headers.Add("Accept","application/json");

        StartCoroutine(WaitForRequest(
                                      new WWW( url, null, headers)
                                      ,     callbackHandler
                                      ,     EVENT_SIGN_IN_SUCCESS
                                      ,        EVENT_SIGN_IN_FAILED
                                      ));
    }


    IEnumerator WaitForRequest(WWW www, XIServiceCallbackHandler callbackHandler, int successEventType, int failedEventType )
    {
        yield return www;

        XServiceEventModel lvServiceEvent = new XServiceEventModel ();
       
        lvServiceEvent.id = www.error == null ? successEventType : failedEventType;
        lvServiceEvent.data = www.text;
        lvServiceEvent.error = www.error;

        // Call Callback Handler
        callbackHandler.xgHandleServiceCallback ( lvServiceEvent );

    }

}



3. Example of  view and using previous classes

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class XSignInViewController : MonoBehaviour, XIServiceCallbackHandler {

    public XGameController gameController;
    public XApiService api;

    public Text txtLogin;
    public Text txtPassword;
    public InputField inpLogin;
    public InputField inpPassword;
    public Button btnSignIn;
    public Button btnBack;
    public Text txtMessageBox;


    // Use this for initialization
    void Start () {

        this.inpLogin.textComponent.text = "";
        this.inpLogin.textComponent.text = "";
        this.txtMessageBox.text = "";
       
    }
   
    // Update is called once per frame
    void Update () {
   
    }


    #region Events

   
    // This method is attached in UnityEditor to Button OnClick
    public void xgDoSignIn(){

        string lvLogin = this.inpLogin.textComponent.text;
        string lvPassword = this.inpPassword.textComponent.text;

        // Very easy call of API
        api.xgSignIn (this, lvLogin, lvPassword);
    }

    #endregion


    #region XIServiceCallbackHandler implementation


    public void xgHandleServiceCallback (XServiceEventModel serviceEvent)
    {
        switch (serviceEvent.id)
        {
       
            case XApiService.EVENT_SIGN_IN_SUCCESS:

            // Save User
            string lvLogin = this.inpLogin.textComponent.text;
            string lvPassword = this.inpPassword.textComponent.text;
            var lvToken = Pathfinding.Serialization.JsonFx.JsonReader.Deserialize<XTokenResponseModel> (serviceEvent.data);

            // DO SOME STAFF

            break;

            case XApiService.EVENT_SIGN_IN_FAILED:
            throw new UnityException ("NOT IMPLEMENTED EVENT_SIGN_IN_FAILED");
            break;

            default:
            throw new UnityException ("EVENT NOT FOUND");
        }
    }

    #endregion

  

}




No comments:

Post a Comment