AWS Mobile Blog

Using Amazon Cognito with Swift: sample app, developer guide, and more.

by Nish Krishnan | on | Permalink | Comments |  Share

Swift, the newest programming language for iOS, OS X, and WatchOS is flexible and easy to learn. Today, we have released a Swift sample app and a corresponding Swift section in the developer guide.  We have also released Swift sample code in the Amazon Cognito console so that developers can choose the language they prefer for iOS development. These releases are all compliant with Swift 2.0.

Importing Amazon Cognito into a Swift project

You can use Cocoapods to import Amazon Cognito into your Swift project.  The following should be added to your Podfile

pod 'AWSCognito'

To use Amazon Cognito in a Swift class, add the following to the top of the class:

import AWSCore
import AWSCognito

Identity and Sync code examples

You can get credentials in Swift by initializing AWSCognitoCredentialsProvider with a region and an identity pool ID. Following that, initialize a configuration object with the credentials provider to access other AWS services. The default service configuration can only be set once.

let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YOUR_IDENTITY_POOL_ID")
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)

AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

To get an identity, you can update the credentials provider login map with a token acquired after logging in with an external provider. The following code sample shows how to do this with Facebook:

let token = FBSDKAccessToken.currentAccessToken().tokenString
credentialsProvider.logins = [AWSCognitoLoginProviderKey.Facebook.rawValue: token]

Then, to get a unique Amazon Cognito ID, you can call getIdentityId() using AWSTask as follows:

// Retrieve your Amazon Cognito ID

credentialsProvider.getIdentityId().continueWithBlock { (task: AWSTask!) -> AnyObject! in

    if (task.error != nil) {
        print("Error: " + task.error.localizedDescription)

    } else {
        // the task result will contain the identity id
        let cognitoId = task.result
    }
    return nil
}

Note: if the Amazon Cognito Identity is already cached, getIdentityId() will return the value of credentialsProvider.identityId.

After you have an Amazon Cognito Identity, you can create datasets with key/value pairs, which can be synchronized across devices using Amazon Cognito Sync.

For example, you can initialize an AWSCognitoCredentialsProvider and access Amazon Cognito Sync in another region by doing the following: 

let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YourIdentityPoolId")
let configuration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialProvider)

AWSCognito.registerCognitoWithConfiguration(configuration, forKey: "USWest2Cognito")

Then, you can initialize an Amazon Cognito Sync client and create a dataset with a key/value pair by doing the following: 

let syncClient = AWSCognito(forKey: "USWest2Cognito")
let dataset = syncClient.openOrCreateDataset("myDataSet")

dataset.setString("my value", forKey:"myKey")

Then, once you have acquired an authenticated identity by updating the logins map and calling getIdentityId(), you can synchronize that dataset so that it is available across all devices using that identity. 

dataset.synchronize().continueWithBlock {(task) -> AnyObject! in

    if task.isCancelled {
        // Task cancelled.

    } else if task.error != nil {
        // Error while executing task

    } else {
        // Task succeeded. The data was saved in the sync store.

    }
    return nil
}

Conclusion

We hope that with the releases of the Swift sample app, the Swift section in the developer guide and Swift sample code in the Amazon Cognito console, more Swift developers will be inclined to adopt Amazon Cognito and incorporate it into their apps. If you get stuck or need help, feel free to reach us on the Amazon Cognito forum.