Navigation

Initialize the StitchAppClient

Overview

In each of the MongoDB Stitch SDKs, there is a StitchAppClient class that offers functionality for communicating with the Stitch backend. This functionality includes methods for authentication, executing functions, and accessing services. In order to setup an Android, iOS, or Web Application to access the StitchAppClient consult the following steps.

StitchAppClient

The Stitch class is the entry point into the Stitch Javascript In-Browser API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient
Use the static Stitch.initializeDefaultAppClient() method to initialize the default StitchAppClient. You typically will call this at the top of your application.
Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

StitchAppClient

The Stitch class is the entry point into the Stitch Javascript In-Browser API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient
Use the static Stitch.initializeDefaultAppClient() method to initialize the default StitchAppClient. You typically will call this at the top of your application.
Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

StitchAppClient

The Stitch class is the entry point into the Stitch Android API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient
Use the static Stitch.getDefaultAppClient() method to obtain the default StitchAppClient initialized at application start using the Stitch App ID specified in your Android application’s strings.xml file.
Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

StitchAppClient

The Stitch class is the entry point into the Stitch iOS API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient

Use the static Stitch.initializeDefaultAppClient method to initialize the default Stitch StitchAppClient client. You should typically call this in the application(_:didFinishLaunchingWithOptions:) method of your project’s AppDelegate.

You can then use the static Stitch.defaultAppClient property.

Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

Procedure

The following sample code demonstrates how to add StitchAppClient to a vanilla JavaScript and HTML project. You should adapt it to fit your application’s architecture.

  1. For Stitch Core SDK functionality and the Remote MongoDB Service, import the following

    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch.js"></script>
    
  2. For additional and more customized dependencies, import any of the following

    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch-core.js"></script>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch-services-aws.js"></script>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch-services-http.js"></script>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch-services-mongodb-remote.js"></script>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch-services-twilio.js"></script>
    
  3. Initialize the app client by calling the Stitch.initializeDefaultAppClient() method with your application’s App ID

    const client = stitch.Stitch.initializeDefaultAppClient('<your-app-id>');
    
  4. You can use the app client to authenticate with Stitch, call functions, and generate service clients, as in the following example:

      <html>
        <head>
          <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch.js"></script>
    
          <script>
            const stitchClient = stitch.Stitch.initializeDefaultAppClient('<your-app-id>');
    
            const mongoClient = stitchClient.getServiceClient(
                stitch.RemoteMongoClient.factory,
                "mongodb-atlas"
            );
    
            const collection = mongoClient.db("dbname").collection("collname");
    
          </script>
        </head>
        <body onload="initApplication()">
          <h1>My App</h1>
          <div id="content">
            Welcome to my basic application.
          </div>
        </body>
      </html>
    
    Replace ``<your-client-app-id>`` with your |stitch| App ID. In
    the |stitch| admin console, you can find your ``App ID``
    in the :guilabel:`Clients` view.
    

React is a widely used JavaScript library for building user interfaces. The following sample code demonstrates how to add StitchAppClient to a React project. You should adapt it to fit your application’s architecture.

  1. Install NPM if you hve not already done so. You can check if you have npm by running the following shell command:

    npm -v
    
  2. For Stitch Core SDK functionality and the Remote MongoDB Service, run the following command in the root directory of your NPM project:

    npm install mongodb-stitch-browser-sdk
    
  3. For additional and more customized dependencies, instead use the following:

    npm install mongodb-stitch-browser-core
    npm install mongodb-stitch-browser-services-aws
    npm install mongodb-stitch-browser-services-http
    npm install mongodb-stitch-browser-services-mongodb-remote
    npm install mongodb-stitch-browser-services-twilio
    
  4. Initialize the app client by calling the Stitch.initializeDefaultAppClient() method with your application’s App ID

    Stitch.initializeDefaultAppClient('<your-app-id>');
    
  5. You can use the app client to authenticate with Stitch, call functions, and generate service clients, as in the following example:

    import React from "react";
    import { render } from "react-dom";
    import { Stitch } from 'mongodb-stitch-browser-sdk'
    
    var YourRootComponent = class extends React.Component {
          render() {
          return (
                <div>
                <NavigationBar/>
                {Stitch.defaultAppClient.auth.isLoggedIn ?
                      <Dashboard /> :
                      <AuthControls }/>
                }
                <Footer/>
                </div>
          );
          }
    };
    
    Stitch.initializeDefaultAppClient('<your-app-id>');
    render(
          <YourRootComponent />
    )
    

For a more comprehensive view of how the StitchAppClient can be initialized and used in a React application, view the ToDo Web App tutorial and associated sample code.

The following sample code demonstrates how to add StitchAppClient to an Android project. You should adapt it to fit your application’s architecture.

  1. We need to add the Stitch Android SDK to our application before we can initialize a client. Add the following line to the Android block of your project’s build.gradle to import the core SDK as well as the Remote MongoDB service client:

    implementation 'org.mongodb:stitch-android-sdk:4.+'
    

    Important

    Stitch supports Android projects that target SDK Version 21 and above. Ensure that the minimum target SDK version for your project falls in this range. You can specify the minimum supported version when you first create your Android project or modify the value for an existing project by setting the minSdkVersion field in build.gradle.

  2. If you want to use services other than MongoDB, or have more customized dependencies, make sure to add that service’s client to build.gradle in addition to the main SDK implementation:

    implementation 'org.mongodb:stitch-android-core:4.+'
    implementation 'org.mongodb:stitch-android-services-aws:4.+'
    implementation 'org.mongodb:stitch-android-services-fcm:4.+'
    implementation 'org.mongodb:stitch-android-services-http:4.+'
    implementation 'org.mongodb:stitch-android-services-mongodb-remote:4.+'
    implementation 'org.mongodb:stitch-android-services-twilio:4.+'
    
  3. Add the following Java compilation settings to the Android block of your project’s build.gradle file:

    compileOptions {
       sourceCompatibility = JavaVersion.VERSION_1_8
       targetCompatibility = JavaVersion.VERSION_1_8
    }
    
  4. The following XML resource configures your application name and points Stitch to your application. Copy the resource XML to your strings.xml resource file, change the application name value, and replace STITCH-APP-ID with your application’s App ID. You can find your App ID on the Clients page of the Stitch UI.

    <!-- app/src/main/res/values/strings.xml -->
    <resources>
         <string name="app_name">Stitch Sample Application Name</string>
         <string name="stitch_client_app_id">STITCH-APP-ID</string>
    </resources>
    

    Note

    Adding your App ID to your strings.xml resource file is optional. You may skip this step and instead make use of the ‘ Stitch.initializeDefaultAppClient() should you want.

  5. The Stitch Android SDK will automatically initialize a default app client based on the App ID you specify in strings.xml. The following sample code demonstrates how to access and use this default StitchAppClient from an Android Activity.

    Note

    You may need to adjust this code to fit your particular application’s architecture.

    import com.mongodb.stitch.android.core.auth.StitchUser;
    import com.mongodb.stitch.android.core.Stitch;
    import com.mongodb.stitch.android.core.StitchAppClient;
    import com.mongodb.stitch.core.auth.providers.anonymous.AnonymousCredential;
    
    public class MainActivity extends AppCompatActivity {
        StitchAppClient stitchClient = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.stitchClient = Stitch.getDefaultAppClient();
    
            Log.d("stitch", "logging in anonymously");
            stitchClient.getAuth().loginWithCredential(new AnonymousCredential()
                    ).continueWithTask(new Continuation<StitchUser, Task<Void>>() {
                        @Override
                        public Task<Void> then(@NonNull Task<StitchUser> task) throws Exception {
                            if (task.isSuccessful()) {
                                Log.d("stitch", "logged in anonymously as user " + task.getResult());
                            } else {
                                Log.e("stitch", "failed to log in anonymously", task.getException());
                            }
                        }
                    })
        }
    }
    

Warning

When it comes to authentication events such as logging in or logging out, the StitchAppClient class is not thread-safe. If your application can perform authentication events from different threads simultaneously, be sure to use a Lock to protect authentication calls to the StitchAppClient.

The following sample code demonstrates how to add StitchAppClient to an iOS project. You should adapt it to fit your application’s architecture.

  1. Install CocoaPods if you have not already done so:

    gem install cocoapods
    

    Note

    CocoaPods 1.1.0+ is required to build Stitch iOS 4.0+

  2. Initialize a Podfile by running the following shell command from the project directory:

    pod init
    
  3. Specify the iOS SDK in the Podfile you initialized to integrate it with your project:

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '11.0'
    use_frameworks!
    
    target '<Your Target Name>' do
        # For core functionality and the Remote MongoDB Service
        pod 'StitchSDK', '~> 5'
    
        # optional: for using the AWS service
        pod 'StitchSDK/StitchAWSService', '~> 5'
        # optional: for using the Firebase Cloud Messaging service
        pod 'StitchSDK/StitchFCMService', '~> 5'
        # optional: for using the HTTP service
        pod 'StitchSDK/StitchHTTPService', '~> 5'
        # optional: for using the twilio service
        pod 'StitchSDK/StitchTwilioService', '~> 5'
    end
    
  4. Install the updated Podfile by running the following shell command from the project directory:

    pod install
    

    Note

    You will need to re-run pod install to install new pods any time you update your Podfile.

  5. Open the .xcworkspace file generated by pod install to access your project with all of its necessary Stitch dependencies automatically linked.

  6. Initialize the app client by calling the Stitch.initializeDefaultAppClient method with your application’s App ID in the application(_:didFinishLaunchingWithOptions:) method of your project’s AppDelegate:

    import StitchCore
    
    // ...
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        // ...
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            do {
                let _ = try Stitch.initializeDefaultAppClient(
                    withClientAppID: "your-client-app-id"
                );
            } catch {
                print("Failed to initialize MongoDB Stitch iOS SDK: \(error.localizedDescription)")
                // note: This initialization will only fail if an incomplete configuration is
                // passed to a client initialization method, or if a client for a particular
                // app ID is initialized multiple times. See the documentation of the "Stitch"
                // class for more details.
            }
    
            return true
        }
    
  7. Once you have initialized the default app client, you can use the static Stitch.defaultAppClient property to access it. You can use the app client to authenticate with Stitch, call functions, and generate service clients, as in the following example:

    import UIKit
    import StitchCore
    import StitchRemoteMongoDBService
    
    class ViewController: UIViewController {
    
        private lazy var stitchClient = Stitch.defaultAppClient!
        private var mongoClient: RemoteMongoClient?
    
        override func viewDidLoad() {
            mongoClient = stitchClient.serviceClient(
                fromFactory: remoteMongoDBServiceClientFactory,
                withName: "mongodb-atlas"
            );
    
            // Perform any Stitch-dependent initialization here, for example:
            if !stitchClient.isAuthenticated() {
                self.displayAuthControls()
            };
    
            let credential = AnonymousCredential.init();
            stitchClient.auth.login(withCredential: credential) {result in
                switch result {
                case .success(_):
                    // Successful authentication
                case .failure(let error):
                    print("failed logging in Stitch. error: \(error)")
                }
            });
    
            // Do any additional setup after loading the view, typically from a nib.
        }
    }
    

Warning

When it comes to authentication events like logging in or logging out, the StitchAppClient class is not thread-safe. If your application can perform authentication events from different threads simultaneously, be sure to use an NSLock to protect authentication calls to the StitchAppClient.