Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Write and Deploy Custom Cloud Code for iOS

DZone's Guide to

How to Write and Deploy Custom Cloud Code for iOS

See how this Custom Code feature can let you change certain parts of your mobile app in the cloud, even in between releases.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

Sometimes, after our app has gone live, we feel the need to change some logic in the app based on market feedback. We sometimes realize that a few changes can increase the app's user retention, runtime performance, etc. But as the app/game is live, nothing can be done until the next release. Here comes the App42 Custom Code feature that allows you to put some code on the cloud, that you may like to alter depending on how well the app is performing.

How it works:

  • Write your custom code in Java, test it, and make a .jar file.
  • Upload the .jar file on the cloud.
  • Call your custom API from the app, and it’s done.

Writing Custom Code

To illustrate the Custom Code feature in detail, I have written a sample iOS project as well as a sample of custom code. First, download the sample iOS project and sample custom code from our GitHub Repo. The downloaded folder has two subfolders namely, App42_CustomCode_jar and App42_CustomCode_Sample. Browse through the App42_CustomCode_jar folder and open CustomCodeSample.java file as follows:

  • Import the App42_CustomCode_jar in your Eclipse IDE.
  • Open Java source file CustomCodeSample.java inside com.shephertz.app42.paas.customcode.sample folder.

What the sample custom code does:

Keynotes:

  • CustomCodeSample class must implement a predefined class Executor, as follows:
[code java]public class CustomCodeSample implements Executor {

@Override
public HttpResponseObject execute(HttpRequestObject request) { }

}[/code]
  • Your custom code must be written inside the method Execute mentioned in above code.

Now let me walk you through the code written inside the Execute method of CustomCodeSample.

[code java]public HttpResponseObject execute(HttpRequestObject request)
 {
        // Fetching request body
JSONObject body = request.getBody();
ServiceAPI sp =null;
try{
                        // Checking required info from request body and their validity

if(body.getString("apiKey")!= null || body.getString("apiKey")!= "" ||

body.getString("secretKey")!= null || body.getString("secretKey")!= ""){
apiKey = body.getString("apiKey");
secretKey = body.getString("secretKey");
sp =  new ServiceAPI(apiKey, secretKey);
        }
if(body.getString("userName")!= null || body.getString("userName")!= "") {
userName = body.getString("userName");
}
if(body.getString("password")!= null || body.getString("password")!= "") {
password = body.getString("password");
}
if(body.getString("emailId")!= null || body.getString("emailId")!= "") {
emailId = body.getString("emailId");
}
if(body.getString("moduleName")!= null || body.getString("moduleName")!= "") {
moduleName =  body.getString("moduleName");
}

}
        catch (JSONException e1)
        {
                        // Logging exception to AppHQ Console

LogService logger = sp.buildLogService();
logger.error("JSON Error :" , e1.getMessage());
}
LogService logger = sp.buildLogService();

// Build Log Service For logging in Your Code

logger.debug(" Recieved Request Body : :" + body.toString(), moduleName);

// Write Your Custom Code Here
// ......//
JSONObject jsonResponse = new JSONObject();
logger.info("Running Custom Code  ", moduleName);
UserService userService = sp.buildUserService();
        try
        {
                       // Creating User

User createUser = userService.createUser(userName, password,
emailId);
if(createUser.isResponseSuccess())
                        {
                               // Authenticating User

User authUser = userService.authenticate(userName,
password);
jsonResponse.put(moduleName,authUser);
}
}
        catch (App42Exception exception)
        {
if (exception.getAppErrorCode() == 2001)
                        {
try
                                {
                                       // Authenticating User

User authCatchUser = userService.authenticate(userName,
password);
jsonResponse.put(moduleName,authCatchUser);
}
                               catch (App42NotFoundException notFoundException)
                               {
                                         // Logging exception to AppHQ Console

logger.error("App42Exception :  ", notFoundException.getMessage());
}
                               catch (JSONException e)
                               {
                                        // Logging exception to AppHQ Console

logger.error("App42Exception : ", e.getMessage());
}
}
else
{
                               // Logging exception to AppHQ Console

logger.error("App42Exception :  ", exception.getMessage());
}
} 
        catch (JSONException e)
        {
                         // Logging exception to AppHQ Console

logger.error("JSON Exception :  ", e.getMessage());
}
// Return JSON Response and Status Code
return new HttpResponseObject(HTTP_STATUS_SUCCESS, jsonResponse);
 }[/code]

In the above code, we are

  • fetching the request body,
  • checking for the parameters sent as the request body,
  • creating a user,
  • authenticating the user, and
  • logging the exception that occurrs if the request fails (that will be available to you inside your AppHQ console).

Deploy Your Custom Code Using the AppHQ Dashboard

  • Login to AppHQ.
  • Go to the AppHQ Menu -> Custom Code -> Deploy Service in the left side panel of the Dashboard.

APPHQ Custom Code

  • Select your App Name from the drop down menu.
  • Browse the Custom Code Jar File that you have created.
  • Enter the name of the CustomCode for this sample, say “CustomCodeTestSample,” click on submit, and you are done.

Accessing the Custom Code From the Client Side

  • Open the Xcode project from the folder App42_CustomCode_Sample that you downloaded above. Browse through the method registerUser in the class called App42ViewController.m
[code java]- (void) registerUser
{
    NSString *_name    = [_nameTextField text];
    NSString *_email   = [_emailTextField text];
    NSString *_pass    = [_passwordTextField text];

    [App42API initializeWithAPIKey:API_KEY andSecretKey:SECRET_KEY];
    CustomCodeService *_service = [App42API buildCustomCodeService];

    /* Creating Request Body*/

    NSDictionary *_requestBody = [NSDictionary dictionaryWithObjectsAndKeys:
                                  API_KEY,@"apiKey",
                                  SECRET_KEY,@"secretKey",
                                  @"CustomCodeTestSample",@"moduleName",
                                  _name,@"userName",
                                  _pass,@"password",
                                  _email,@"emailId",nil];

    App42Response *_response = [_service runJavaCode:@"CustomCodeTestSample" requestBody:_requestBody];
    NSLog(@"[_response strResponse] = %@",[_response strResponse]);
    [_responseTextView setText:[_response strResponse]];
}[/code]
  • Initialize the App42 API.
  • Create a custom code request body as in the above code.
  • Call the runJavaCode API of our CustomCodeService, and you are done.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
mobile ,mobile app development

Published at DZone with permission of Rajeev Ranjan. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}