IOS App via AWS

From ESE205 Wiki
Revision as of 01:19, 13 December 2016 by Andrewsweren (talk | contribs)
Jump to navigation Jump to search

The Line of Least Resistance

Overview

In order to make an iOS app for our project, we utilized Amazon Web Services. This tutorial will explain how to call functions from a project created on Xcode, Apple's app development software.

An important thing to note is that AWS updated their protocol for calling functions, and saving them in Cloud Logic, to a much more sophisticated version in late 2016. We were able to use the original protocol because we had created the project before the switch. Since we didn't actually use the new system, additional research will have to be done for creating and using APIs, but there are a lot of YouTube and AWS tutorials for the old system so we expect there will be more help for the new system soon.

A great guide to learn the basics of Swift and simple tools for creating an app on Xcode can be found here on Apple's website, and YouTube has some very helpful tutorials for more specifics.

Setting Up Your Project

Go to the AWS home page, and enter your Amazon.com credentials (if you don't have an Amazon account, you'll have to create one).

Click Mobile Hub, click Create a new mobile project, and create your project. Aws.png

Next, decide which features you want in your app. We utilized NoSQL Database and Cloud Logic, but you can also do User Sign In, Push Notifications, etc. For NoSQL Database, click the plus button, and click Enable NoSQL Database and add as many custom tables as you need. Look here for instructions on setting up your Database.

Features.png

For Cloud Logic, click the plus button and Create new API.

Click "Create new API."

Note: this is where they made the changes to the system. Before they had "legacy" Lambda Functions that you could simply write code to call, but they have employed a new system with "paths" that allow you to do more. Although this will need adjustment in order to fit the new system, this is the code we used to call our Lambda Function:

@IBAction func handleSubmit(sender: AnyObject) {
        let functionName = "testfunction2"
        let early = earlyPickerData[earlypicker.selectedRowInComponent(0)]
        let late = latePickerData[latepicker.selectedRowInComponent(0)]
        let size = (sizeTextField.unwrappedText)
        let name = (nameTextField.unwrappedText)

let inputText =
            "{\n  \"r\":\"Killer Burger\",\n  \"early\":\""+early+"\",\n  \"late\":\""+late+"\",\n  \"size\":"+size+",\n  \"name\":\""+name+"\"\n}"
        
        print("Function Name: \(functionName)")
        let jsonInput = inputText.makeJsonable()
        let jsonData = jsonInput.dataUsingEncoding(NSUTF8StringEncoding)!
        var parameters: [String: AnyObject]
        do {
            let anyObj = try NSJSONSerialization.JSONObjectWithData
            (jsonData, options: []) as! [String: AnyObject]
            parameters = anyObj
        } catch let error as NSError {
            resultTextView.text = "JSON request is not well-formed."
            print("json error: \(error.localizedDescription)")
            return
        }
        print("Json Input: \(jsonInput)")
        
               AWSCloudLogic.defaultCloudLogic().invokeFunction(functionName,
            withParameters: parameters, completionBlock: {(result: AnyObject?, error: NSError?) -> Void in
                if let result = result {
                    dispatch_async(dispatch_get_main_queue(), {
                        print("KillerBurgerViewController: Result: \(result)")
                        self.resultTextView.text = prettyPrintJson(result)
                    })
                }
                var errorMessage: String
                if let error = error {
                    if let cloudUserInfo = error.userInfo as? [String: AnyObject],
                        cloudMessage = cloudUserInfo["errorMessage"] as? String {
                        errorMessage = "Error: \(cloudMessage)"
                    } else {
                        errorMessage = "Error occurred in invoking the Lambda Function. No error message found."
                    }
                    dispatch_async(dispatch_get_main_queue(), {
                        print("Error occurred in invoking Lambda Function: \(error)")
                        self.activityIndicator.stopAnimating()
                        self.resultTextView.text = errorMessage
                        let alertView = UIAlertController(title: NSLocalizedString("Error", comment: "Title bar for error alert."), message: error.localizedDescription, preferredStyle: .Alert)
                        alertView.addAction(UIAlertAction(title: NSLocalizedString("Dismiss", comment: "Button on alert dialog."), style: .Default, handler: nil))
                        self.presentViewController(alertView, animated: true, completion: nil)
                    })
                }
        })
    }

Creating a Project in Xcode

Now that you have a project set up in AWS, Download Xcode from the Apple App Store (warning: it takes up a ton of space (5-10 GB), so make sure you have a lot to spare).

At the top of your project in AWS, click Integrate with my app. Integrate.png

You can either integrate the features you chose with a project started from scratch in Xcode, or you can download a sample app from AWS and adapt from there. We would highly recommend the latter option because there are lots of helper codes, frameworks, and software development kits that you have to load into your app if you do it from scratch.

If you decide to use their Sample App, click Download a sample app, and open the Zip file.

Sampleapp.png

You now have an app with the capability to call Lambda functions, populate a database, and do whatever other features you chose. You can look at the Storyboards in your Xcode project to see the pre-made app has, and you can click the play button in the top left to open the Simulator and test functions. Storyboard.png

You can also run the simulator on your iOS device, but I had to follow these directions to get around the developer licensing issue (we were able to do the whole project without spending any money on software or development).

Connecting to an AWS Database

Lambda functions can be done in either Java or Python. We chose to do ours in Java.

Open Eclipse. At the top of your screen, go to Help -> Install New Software. Enter the necessary URL provided on the AWS website and follow the instructions. When it asks you to install sample code, make sure to download a sample Lambda Function.

Add any instance variables you might need at the top:

private static AmazonDynamoDBClient dynamoDB; //this one is already created
private static Map<String, Restaurant> map;

Add your credentials. This will be needed in order to send the information to your AWS account. Find your credentials in the AWS console by clicking on your account name, and clicking on My Security Credentials. Click Continue to Security Credentials. Expand the tab saying Access Keys, and click Create New Access Key and follow the instructions. You will see an Access Key ID and a Secret Key ID. Keep these in a secure place so that you can access them, and place them in this code:

String access_key_id = "********************"; //replaced with stars for privacy reasons
String secret_key_id = "****************************************"; //replaced with stars for privacy reasons
BasicAWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_key_id);

dynamoDB = new AmazonDynamoDBClient(credentials);
Region usEast1 = Region.getRegion(Regions.US_EAST_1);
dynamoDB.setRegion(usEast1);

Modify any other instance variables you may have created.

The entire function must be written within a try and catch statement. It should look something like this.

              try {
              //your code goes here
              } catch (AmazonServiceException ase) {
			System.out.println("Caught an AmazonServiceException, which means your request made it "
					+ "to AWS, but was rejected with an error response for some reason.");
			System.out.println("Error Message:    " + ase.getMessage());
			System.out.println("HTTP Status Code: " + ase.getStatusCode());
			System.out.println("AWS Error Code:   " + ase.getErrorCode());
			System.out.println("Error Type:       " + ase.getErrorType());
			System.out.println("Request ID:       " + ase.getRequestId());
			return "AmazonServiceException"; //return statement only for debugging purposes
		} catch (AmazonClientException ace) {
			System.out.println("Caught an AmazonClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with AWS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ace.getMessage());
			return "AmazonClientException"; //return statement only for debugging purposes
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "InterruptedException"; //return statement only for debugging purposes
		}

Initialize your tables:

String tableName = "TableName";
//------------------This section of code creates a table----------------
// Create a table with a primary hash key named 'name', which holds a string
CreateTableRequest Table = new CreateTableRequest().withTableName(tableName).withKeySchema(new KeySchemaElement().withAttributeName("YourKey").withKeyType(KeyType.HASH)).withAttributeDefinitions(new AttributeDefinition().withAttributeName("YourKey").withAttributeType(ScalarAttributeType.S)).withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

// Create table if it does not exist yet
TableUtils.createTableIfNotExists(dynamoDB, Table);

// wait for the table to move into ACTIVE state
TableUtils.waitUntilActive(dynamoDB, tableName);

Write whatever code is necessary to perform the function.

Before uploading the function, you need to create a role. Log into AWS and select IAM. Go to the tab Roles. Click Create New Role.

In the AWS console, select Lambda. Click the button saying Create a Lambda function. Select your blueprint and follow the instructions.

Finally, you must create a bucket. Select S3 on the AWS Console, and click Create Bucket. Name the bucket and select the region you are in. Note that the bucket must have a unique name.

Once the code is written, right click on a part of the code where there is no text. Hover over the tab that says AWS Lambda. From there select Upload Function to AWS Lambda. Select the Lambda Function you created and the region that matches the one in your code. Hit Next. For the role and bucket, select the ones you created. Click Finish

Screen Shot 2016-12-12 at 7.10.17 PM.png

After the function is uploaded, right click again on a part of the code without text, hover over AWS Lambda, but this time select Run Function on AWS Lambda.

Screen Shot 2016-12-12 at 7.18.34 PM.png

Delete everything but the opening and closing brackets in the sample input. Replace everything with the information you need for the input. Make sure to place a comma after every line except for the last. If this is not done, an error will be thrown.

You can check to see if the information was sent in your AWS console under DynamoDB. From there click Tables and check to make sure the information is there.