From 831af65b8a3642284eb0185dde91eb2c45c50a00 Mon Sep 17 00:00:00 2001 From: Richard Threlkeld Date: Sun, 28 Oct 2018 10:38:14 -0700 Subject: [PATCH] update(GettingStarted-iOS): Proposed flow and ported manual SDK configuration. Still need to discuss pulling Objective-C and Carthage --- _config.yml | 12 ++- ios/manualsetup.md | 123 ++++++++++++++++++++++ ios/start.md | 257 +++++++++++++++++++++++++++++++++++---------- 3 files changed, 338 insertions(+), 54 deletions(-) create mode 100644 ios/manualsetup.md diff --git a/_config.yml b/_config.yml index 9642d83f3d2..099d4e87187 100644 --- a/_config.yml +++ b/_config.yml @@ -349,7 +349,17 @@ ios_category_list: url: https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt - title: Custom Plugin url: - + - category: Manual SDK Configuration + title: SDK Configuration + excerpt: Low level config + base_url: '/ios/manualsetup' + subs: + - title: Manual SDK Setup + excerpt: Setup Options for the SDK + cta: Read more + class: aws-icon-ps-60-circular-circuit + url: '/ios/manualsetup' + category_list: - category: SetupAndInstallation title: Setup & Installation diff --git a/ios/manualsetup.md b/ios/manualsetup.md new file mode 100644 index 00000000000..fa1979f70c3 --- /dev/null +++ b/ios/manualsetup.md @@ -0,0 +1,123 @@ +# Setup Options for the SDK + +The AWS SDK contains [high level client interfaces](./start) for quickly adding common features and functionality to your app. You can also manually add the generated AWS service interfaces for direct interaction if you have custom or advanced requirements. + +## CocoaPods setup + +The AWS Mobile SDK for iOS is available through [CocoaPods](https://cocoapods.org). Install CocoaPods by running the following commands from the folder containing your projects `*.xcodeproj` file: + +```bash +gem install cocoapods +pod setup +pod init +``` + +In your project directory (the directory where your `*.xcodeproj` file is), open the empty text file named `Podfile`. Replace `myAppName` with your app name. You can also remove pods for services that you don't use. For example, if you don't use `AWSAutoScaling`, remove or do not include the `AWSAutoScaling` pod. + +```bash +source 'https://github.com/CocoaPods/Specs.git' + +platform :ios, '8.0' +use_frameworks! + +target :'YOUR-APP-NAME' do + pod 'AWSAuth' + pod 'AWSAuthCore' + pod 'AWSAuthUI' + pod 'AWSAutoScaling' + pod 'AWSCloudWatch' + pod 'AWSCognito' + pod 'AWSCognitoAuth' + pod 'AWSCognitoIdentityProvider' + pod 'AWSCognitoIdentityProviderASF' + pod 'AWSCore' + pod 'AWSDynamoDB' + pod 'AWSEC2' + pod 'AWSElasticLoadBalancing' + pod 'AWSFacebookSignIn' + pod 'AWSGoogleSignIn' + pod 'AWSIoT' + pod 'AWSKMS' + pod 'AWSKinesis' + pod 'AWSLambda' + pod 'AWSLex' + pod 'AWSLogs' + pod 'AWSMachineLearning' + pod 'AWSMobileAnalytics' + pod 'AWSMobileClient' + pod 'AWSPinpoint' + pod 'AWSPolly' + pod 'AWSRekognition' + pod 'AWSS3' + pod 'AWSSES' + pod 'AWSSNS' + pod 'AWSSQS' + pod 'AWSSimpleDB' + pod 'AWSUserPoolsSignIn' +end +``` + +Once complete, run `pod install` and open the `*.xcworkspace` with Xcode and **build** your project to start using the SDK. Once you have created a workspace, always use `*.xcworkspace` to open the project instead of `*.xcodeproj`. + +Whenever a new version of the SDK is released you can update by running `pod update` and rebuilding your project to use the new features. + +## Logging + +As of version 2.5.4 of this SDK, logging utilizes [CocoaLumberjack SDK](https://github.com/CocoaLumberjack/CocoaLumberjack), a flexible, fast, open source logging framework. It supports many capabilities including the ability to set logging level per output target, for instance, concise messages logged to the console and verbose messages to a log file. + +CocoaLumberjack logging levels are additive such that when the level is set to verbose, all messages from the levels below verbose are logged. It is also possible to set custom logging to meet your needs. For more information, see [CocoaLumberjack Logging Levels](https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomLogLevels.md). + +You can change the logging level to suit the phase of your development cycle by importing AWSCore and calling: + +```swift +AWSDDLog.sharedInstance().logLevel = .verbose +``` + +The following logging level options are available: + +- `.off` +- `.error` +- `.warning` +- `.info` +- `.debug` +- `.verbose` + +We recommend setting the log level to `.off` before publishing to the App Store. + +CocoaLumberjack can direct logs to file or used as a framework that integrates with the Xcode console. For example: + +```swift +//File Logger example +let fileLogger: AWSDDFileLogger = AWSDDFileLogger() // File Logger +fileLogger.rollingFrequency = TimeInterval(60*60*24) // 24 hours +fileLogger.logFileManager.maximumNumberOfLogFiles = 7 +AWSDDLog.add(fileLogger) + + +//Console example +AWSDDLog.add(AWSDDTTYLogger.sharedInstance) // TTY = Xcode console +``` + +## DocSet for Xcode + +Open the macOS terminal and go to the directory containing the expanded archive. For example: + +```bash +$ cd ~/Downloads/aws-ios-sdk-2.5.0 +``` + +**Note**: Replace 2.5.0 in the preceding example with the version number of the AWS Mobile SDK for iOS that you downloaded. + +Create a directory called `~/Library/Developer/Shared/Documentation/DocSets`: + +```bash +$ mkdir -p ~/Library/Developer/Shared/Documentation/DocSets +``` + +Copy (or move) `documentation/com.amazon.aws.ios.docset` from the SDK installation files to the directory you created in the previous step: + +```bash +$ mv documentation/com.amazon.aws.ios.docset ~/Library/Developer/Shared/Documentation/DocSets/ +``` + +If Xcode was running during this procedure, restart Xcode. To browse the documentation, go to **Help**, click **Documentation and API Reference**, and select **AWS Mobile SDK for iOS v2.0 Documentation** (where '2.0' is the appropriate version number). \ No newline at end of file diff --git a/ios/start.md b/ios/start.md index d433e5703bf..a74a37280ab 100755 --- a/ios/start.md +++ b/ios/start.md @@ -1,60 +1,86 @@ # Getting Started -Get started building a cloud-powered iOS app using the AWS Amplify CLI and the AWS SDK for iOS. This page guides you through setting up an initial backend and integrating the SDK into your app. +Build an iOS app using the AWS Amplify CLI and the AWS SDK for iOS. The Amplify CLI lets you quickly add backend features to your application so that you can focus on your application code. This page guides you through setting up an initial backend and integration into your app. -## Step 0: Set Up Your Development Environment +## Prerequisites -We strongly recommend that you use the Amplify CLI for building the serverless backend for your app. If you have already installed the CLI, skip ahead to [Step 2](./add-aws-mobile-sdk-basic-setup). +[Install Xcode](https://developer.apple.com/xcode/downloads/) version 8.0 or later. + +Install the Amplify CLI. If you have already installed the CLI, skip ahead to [Step 2](./add-aws-mobile-sdk-basic-setup). * [Sign up for an AWS Account](https://portal.aws.amazon.com/billing/signup?redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start). -* Install [Node.js](https://nodejs.org/) and npm (if they are not already installed). +* Install [Node.js](https://nodejs.org/) and [npm](https://www.npmjs.com/get-npm) if they are not already installed. -> Verify that you are running at least Node.js version 8.x or greater and npm version 5.x or greater by running :code:`node -v` and :code:`npm -v` in a terminal/console window. Older versions aren't supported and might generate errors. +Verify that you are running at least Node.js version 8.11+ or greater and npm version 5.x or greater by running `node -v` and `npm -v` in a terminal/console window. +{: .callout .callout--action} To install and configure the Amplify CLI globally, run the following commands in a terminal window. +Install and configure the Amplify CLI. + ```bash $ npm install -g @aws-amplify/cli $ amplify configure ``` -* Choose the iOS app project you want to integrate with an AWS backend. -* [Install Xcode](https://developer.apple.com/xcode/downloads/) version 8.0 or later. +Note: These commands will install the CLI globally. If you're using Windows, the CLI currently supports Windows Subsystem for Linux. +{: .callout .callout--action} + ## Step 1: Create a new app Follow [these steps](https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/BuildABasicUI.html) to create an iOS application using Swift. -## Step 2: Install amplify +Install Cocoapods. From a terminal window navigate into your Xcode project's application directory and run the following: ```bash -$ npm install --save aws-amplify +sudo gem install cocoapods +pod init ``` -## Step 3: Set Up Your Backend +Open the created `Podfile` in a text editor and add the pod for core AWS Mobile SDK components to your build. + +``` +platform :ios, '9.0' +target :'YOUR-APP-NAME' do + use_frameworks! -1. The CLI prompts you for configuration parameters. + pod 'AWSCore', '~> 2.6.13' - In a terminal window, navigate to your project folder (the folder that typically contains your project level `xcodeproj` file), and add the SDK to your app. + # other pods +end +``` + +Install dependencies by running the following: ```bash -$ cd ./YOUR_PROJECT_FOLDER -$ amplify init +pod install --repo-update ``` -2. To create your backend AWS resources and add a configuration file to your app, run the following: +Close your Xcode project and reopen it using `./YOUR-PROJECT-NAME.xcworkspace` file. Remember to always use `./YOUR-PROJECT-NAME.xcworkspace` to open your Xcode project from now on. **Build your Xcode project**. + + +## Step 2: Set Up Your Backend + +Create new AWS backend resources and pull the AWS services configuration into the app. In a terminal window, navigate to your project folder (the folder that contains your `xcodeproj` file), and run the following command (for this app, accepting all defaults is OK): ```bash -$ amplify push +$ cd ./YOUR_PROJECT_FOLDER +$ amplify init #accept defaults +$ amplify push #creates configuration file ``` -In the Finder, navigate to the folder containing your app `.xcodeproj` file. From there, drag :code:`awsconfiguration.json` to Xcode under the top Project Navigator folder (the folder name should match your Xcode project name). In the `Options` dialog box that appears, do the following: +In the Finder, drag `awsconfiguration.json` into Xcode under the top Project Navigator folder (the folder name should match your Xcode project name). When the `Options` dialog box that appears, do the following: * Clear the `Copy items if needed` check box. * Choose `Create groups`, and then choose `Next`. -3. To verify that the CLI is set up for your app, run the following command. The CLI displays a status table with no resources listed. As you add categories to your app, backend resources created for your app are listed in this table. +## Step 3: How it Works + +Rather than configuring each service through a constructor or constants file, the AWS SDKs for iOS support configuration through a centralized file called `awsconfiguration.json` which defines all the regions and service endpoints to communicate. Whenever you run `amplify push`, this file is automatically created allowing you to focus on your Swift application code. On iOS projects the `awsconfiguration.json` will be placed into the root directory and you will need to add it to your XCode project. + +To verify that the CLI is set up for your app, run the following command. ```bash $ amplify status @@ -62,62 +88,187 @@ In the Finder, navigate to the folder containing your app `.xcodeproj` file. Fro | -------- | ------------- | --------- | --------------- | ``` - Use the steps in the next section to configure the connection between your app and the serverless backend. - -## Step 4: Connect to Your Backend +The CLI displays a status table with no resources listed. As you add feature categories to your app and run `amplify push`, backend resources created for your app are listed in this table. -Perform the following steps to set up a connection to AWS services that you'll use in the Get Started section of this guide. +## Step 4: Add API and Database -1. Install Cocoapods. From a terminal window run the following: +Add a GraphQL API to your app and automatically provision a database with the following command (accepting all defaults is OK): -``` -sudo gem install cocoapods +```bash +$ amplify add api #select GraphQL ``` -2. Create `Podfile`. From a terminal window, navigate to the directory that contains your project's `.xcodeproj` file and run the following: +The `add api` flow above will ask you some questions, like if you already have an annotated GraphQL schema. If this is your first time using the CLI select **No** and let it guide you through the default project **"Single object with fields (e.g., “Todo” with ID, name, description)"** as it will be used in the code generation examples below. Later on you can always change it. This process creates an AWS AppSync API and connects it to an Amazon DynamoDB database. -``` -pod init +Since you added an API the `amplify push` process will automatically enter the codegen process and prompt you for configuration. Accept the defaults which generate a file named `API.swift`. Drag and drop this file from you `Finder` to the Xcode project and update your Podfile to include `AWSAppSync`: + +```bash +target 'MyApp' do ##Replace MyApp with your application name + use_frameworks! + + pod 'AWSAppSync' + +end ``` -3. Open `Podfile` in a text editor and add the pod for core AWS Mobile SDK components to your build. +Run `pod install` and **build your app**. +## Step 5: Integrate into your app + +initialize the AppSync client inside your application delegate: + +```swift +import AWSAppSync + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var appSyncClient: AWSAppSyncClient? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + //You can choose your database location + let databaseURL = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent("database_name") + + do { + //AppSync configuration & client initialization + let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncClientInfo: AWSAppSyncClientInfo(),databaseURL: databaseURL) + appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig) + } catch { + print("Error initializing appsync client. \(error)") + } + //other methods + return true +} ``` -platform :ios, '9.0' -target :'YOUR-APP-NAME' do - use_frameworks! - pod 'AWSCore', '~> 2.6.13' +Next, in your application code where you wish to use the AppSync client (like your View Controller) reference this in the `viewDidLoad()` lifecycle method: - # other pods -end +```swift +import AWSAppSync + +class Todos: UIViewController{ + //Reference AppSync client + var appSyncClient: AWSAppSyncClient? + + override func viewDidLoad() { + super.viewDidLoad() + let appDelegate = UIApplication.shared.delegate as! AppDelegate + appSyncClient = appDelegate.appSyncClient + } +} ``` -4. Install dependencies by running the following: +You can now add data to your database with a mutation: + +```swift + func runMutation(){ + let mutationInput = CreateTodoInput(name: "Use AppSync", description:"Realtime and Offline") + appSyncClient?.perform(mutation: CreateTodoMutation(input: mutationInput)) { (result, error) in + if let error = error as? AWSAppSyncClientError { + print("Error occurred: \(error.localizedDescription )") + } + if let resultError = result?.errors { + print("Error saving the item on server: \(resultError)") + return + } + } + } ``` -pod install --repo-update + +Next, query the data: + +```swift + func runQuery(){ + appSyncClient?.fetch(query: ListTodosQuery()) {(result, error) in + if error != nil { + print(error?.localizedDescription ?? "") + return + } + result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) } + } + } +``` + +You can also setup realtime subscriptions to data: + +```swift + var discard: Cancellable? + + func subscribe() { + do { + discard = try appSyncClient?.subscribe(subscription: OnCreateTodoSubscription(), resultHandler: { (result, transaction, error) in + if let result = result { + print(result.data!.onCreateTodo!.name + " " + result.data!.onCreateTodo!.description!) + } else if let error = error { + print(error.localizedDescription) + } + }) + } catch { + print("Error starting subscription.") + } + } ``` - If you encounter an error message that begins `[!] Failed to connect to GitHub to update the CocoaPods/Specs . . .`, and your internet connectivity is working, you might need to [update openssl and Ruby](https://stackoverflow.com/questions/38993527/cocoapods-failed-to-connect-to-github-to-update-the-cocoapods-specs-specs-repo/48962041#48962041). +Call the `runMutation()`, `runQuery()`, and `subscribe()` methods from your app code, such as from a button click or when your app starts in `viewDidLoad()`. You will see data being stored and retrieved in your backend from the Xcode console. -5. The command `pod install` creates a new workspace file. Close your Xcode project and reopen it using `./YOUR-PROJECT-NAME.xcworkspace`. - - Use **ONLY** your .xcworkspace - - Remember to always use `./YOUR-PROJECT-NAME.xcworkspace` to open your Xcode project from now on. +## Next Steps -6. Rebuild your app after reopening it in the workspace to resolve APIs from new libraries called in your code. This is a good practice any time you add import statements. +🎉 Congratulations! Your app is built, with a realtime backend using AWS AppSync. + +What next? Here are some things to add to your app: + +* [Analytics](./analytics) +* [Authentication](./authentication) +* [Push Notification](./push-notifications) +* [User File Storage](./storage) +* [Serverless APIs](./api) +* [Messaging](./messaging) + +**Existing AWS Resources** + +If you want to use your existing AWS resources with your app you will need to **manually configure** your app with an `awsconfiguration.json` file in your code. For example, if you were using Amazon Cognito Identity, Cognito User Pools, AWS AppSync, or Amazon S3: + +```xml +{ + "CredentialsProvider": { + "CognitoIdentity": { + "Default": { + "PoolId": "XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab", + "Region": "XX-XXXX-X" + } + } + }, + "CognitoUserPool": { + "Default": { + "PoolId": "XX-XXXX-X_abcd1234", + "AppClientId": "XXXXXXXX", + "AppClientSecret": "XXXXXXXXX", + "Region": "XX-XXXX-X" + } + }, + "AppSync": { + "Default": { + "ApiUrl": "https://XXXXXX.appsync-api.XX-XXXX-X.amazonaws.com/graphql", + "Region": "XX-XXXX-X", + "AuthMode": "AMAZON_COGNITO_USER_POOLS" + } + }, + "S3TransferUtility": { + "Default": { + "Bucket": "BUCKET_NAME", + "Region": "XX-XXXX-X" + } + } +} +``` -Your app is now ready for you to add cloud-powered features. We recommend [adding analytics](./analytics) as your first feature. +In the configuration above, you would need to set the appropriate values such as `Region`, `Bucket`, etc. -## Step 5: Initialize the SDK +**AWS SDK Interfaces** -## Step 6: Concepts (awsconfig, manual credentials) +For working with other AWS services you can use service interface objects directly via the generated SDK clients. -## Next Steps +To work with service interface objects, your Amazon Cognito users' [IAM role](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html) must have the appropriate permissions to call the requested services. +{: .callout .callout--warning} -* [Add Analytics](./analytics) -* [Add User Sign-in](./authentication) -* [Add Push Notification](./push-notifications) -* [Add User File Storage](./storage) -* [Add Serverless Backend](./api) -* [Add Cloud Logic](./api) -* [Add Messaging](./messaging) +You can call methods on any AWS Service interface object supported by the AWS iOS SDK by passing your credentials from the AWSMobileClient to the service call constructor. See [Manual SDK Setup](./manualsetup) for more information. \ No newline at end of file