IOS App via AWS

From ESE205 Wiki
Revision as of 02:26, 12 December 2016 by Devon.essick (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, but 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 I expect there will be more help for the new system soon.

A great tutorial about the basics of Swift and simple tools for creating an app on Xcode can be found here on Apple's website, and YouTube has great tutorials for more specifics.

Setting Up Your Project

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

Under "Mobile Services," click Mobile Hub, click "Create a new mobile project", enter a project name, and create your project.

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 then see this page to set up the server.

For Cloud Logic, click the plus button and create a new API. Note: this is where they made the changes to the system. Before they had "legacy" functions that you could simply enter code to be called, 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 your project set up in AWS, you create your project in Xcode, which can be downloaded 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." You can either integrate the features you chose with an project you start from scratch in Xcode, or you can download a sample app from AWS and adapt from there. I 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.

Click "Download a sample app," and open the Zip file.

You now have an app with the capability to call Lambda functions, populate a database, and whatever other features you chose. You can look at the Storyboards under MySampleApp -> MySampleApp -> Demo -> Cloud Logic/UserIdentity/etc to see the pre-made app they have, and you can click the play button in the top left to open the Simulator and test functions. You can also run the simulator on your iOS device, but I had to follow these directions to get around the developer licensing issue.

Connecting to a AWS Database