Use AWSMobileClient without `awsconfiguration.json`in iOS

Viewed 4630

I'd like to authenticate an iOS device to use AppSync/S3 services via Cognito user pools. The AWSMobileClient provides some nice conveniences but the initialization requires that you're bundle have an awsconfiguration.json file -- which our application will define dynamically. Is there a way to configure that manually?

3 Answers

The current solution is to use the multi-environment workflow from the CLI. https://aws-amplify.github.io/docs/cli/multienv?sdk=ios


Edit

If the multi-environment workflow from the Amplify team doesn't work for you, what you can do is create debug and prod versions of your config, and then create a build phase that copies the correct one based on your build settings (debug vs release, etc). This is working extremely well for one of my projects.

Config files

Build phases

#export; #Prints list of all xcode variables with values
printf "$CONFIGURATION\n";

if [ "$CONFIGURATION" = "Debug" ]; then
printf "creating debug configuration";
cp -r "$PROJECT_DIR/awsconfiguration-debug.json" "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app/awsconfiguration.json"
else 
printf "creating production configuration";
cp -r "$PROJECT_DIR/awsconfiguration-prod.json" "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app/awsconfiguration.json"
fi

As of AWS iOS SDK 2.11.0 (9th September 2019) it is now possible to configure without an awsconfiguration.json file.

It's even documented in the amplify documentation here

See also my answer to a related question

Here's a specific solution:

extension AWSMobileClient {
    convenience init?(configuration url: URL) {
        guard let data = try? Data(contentsOf: url) else { return nil }
        guard let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else { return nil }

        self.init(configuration: dict)
    }

    convenience init?(configuration name: String) {
        guard let url = Bundle.main.url(forResource: name, withExtension: "json") else {
            return nil
        }

        print("INITIALIZING AWSMobileClient [\(name)]")
        self.init(configuration: url)
    }
}

To use it, you can have as many different awsconfiguration-XXX.json files as you need, and at runtime you initialize with the one you want by:

let mobileClient = AWSMobileClient(configuration: "awsconfiguration-XXX")
mobileClient.initialize { (userState, error) in ... }
Related