Overview

Cloud DB, a service of AppGallery Connect, can keep your device-cloud data in sync, and provide you with unified data models, and various data management APIs. With bolstered data accessibility, reliability, consistency, and security, you can achieve seamless data synchronization between the device and cloud, to build apps that support device-cloud and multi-device data synergy, and ensure that services remain available even when users are offline.

What You Will Create

In this codelab, you will create an iOS app that integrates Cloud DB of AppGallery Connect, which allows users to add and query data.

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

An iPhone or a simulator for testing

To integrate Cloud DB of AppGallery Connect, you need to complete the following preparations:

For details, please refer to Integration Preparations.

Before integrating the Cloud DB SDK, you need to first enable Cloud DB. The procedure is as follows:

  1. Sign in to AppGallery Connect and click My projects.
  2. Click the project for which you need to enable Cloud DB.
  3. Go to Build > Cloud DB. On the Cloud DB page, click Enable now.
  4. Set a data processing location on the displayed page.

You need to integrate the Cloud DB SDK into your Xcode project with CocoaPods.

  1. Sign in to AppGallery Connect and click My projects.
  2. Click your project and select an app for SDK integration from the app drop-down list on the top.
  3. Go to Project settings > General information. In the App information area, download the agconnect-services.plist file.
  4. Copy the agconnect-services.plist file to your project.
  5. (Optional) Open the CLI and navigate to the location of the Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.
    cd project-directory pod init
  6. Add the dependencies on AGConnectDatabase and AGConnectAuth to the Podfile.
    target 'CloudDBDemo' do pod 'AGConnectDatabase' pod 'AGConnectAuth' end
  7. Install the pods and open the .xcworkspace file to view the project.
    pod install

    The following figure shows the result after installation.

You will create an app used for managing books and design its UI according to the following figure.

The layout code for the sign-in page is as follows:

@interface BMLoginView () @property (nonatomic, strong) UIImageView *iconImageView; @property (nonatomic, strong) UILabel *tipLabel; @property (nonatomic, strong) CAGradientLayer *gradientLayer; @end @implementation BMLoginView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self coreGradientLayer]; [self setupUI]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; self.iconImageView.frame = CGRectMake((self.frame.size.width - 40) / 2, 20, 40, 40); self.tipLabel.frame = CGRectMake(0, CGRectGetMaxY(self.iconImageView.frame) + 18, self.frame.size.width, 20); } - (void)setupUI { UIImageView *iconImageView = [[UIImageView alloc] init]; iconImageView.image = [UIImage imageNamed:@"icon_account"]; [self addSubview:iconImageView]; self.iconImageView = iconImageView; UILabel *tipLabel = [[UILabel alloc] init]; tipLabel.textAlignment = NSTextAlignmentCenter; tipLabel.textColor = [UIColor darkGrayColor]; tipLabel.text = NSLocalizedString(@"LoginAdminText", nil); [self addSubview:tipLabel]; self.tipLabel = tipLabel; self.layer.cornerRadius = 5.f; self.layer.masksToBounds = YES; } - (void)coreGradientLayer { CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.colors = @[(__bridge id)[UIColor grayColor].CGColor, (__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor grayColor].CGColor]; gradientLayer.startPoint = CGPointMake(0, 0); gradientLayer.endPoint = CGPointMake(1.0, 0); gradientLayer.frame = self.bounds; [self.layer insertSublayer:gradientLayer below:self.layer]; self.gradientLayer = gradientLayer; } - (void)loginSuccess { self.tipLabel.text = @"Administrator"; } @end

The sample code in this codelab uses the anonymous sign-in mode. Therefore, you need to enable the anonymous authentication mode of Auth Service in AppGallery Connect. Otherwise, sign-in fails.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Auth Service. If it is the first time that you use Auth Service, click Enable now.
  4. Click the Authentication mode tab and enable Anonymous account in the Operation column.
  5. Call the relevant methods of Auth Service in the project and ensure that your app has been signed in anonymously before using the functions of Cloud DB. Sample code:
    AGCAuth *agcAuth = [AGCAuth getInstance]; NSLog(@"start agc inanonymously login"); if (agcAuth.currentUser == nil) { NSLog(@"agc current user is nil"); HMFTask<AGCSignInResult *> *loginTask = agcAuth.signInAnonymously; [[loginTask addOnSuccessCallback:^(AGCSignInResult *_Nullable result) { NSLog(@"agc sign inanonymously success."); self.loginState = YES; if (complete) { complete(YES, nil); } }] addOnFailureCallback:^(NSError *_Nonnull error) { NSLog(@"agc sign inanonymously failed. error: %@", error); if (complete) { complete(NO, error); } }]; } else { NSLog(@"agc has login."); self.loginState = YES; if (complete) { complete(YES, nil); } }
  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Cloud DB.
  4. Click Add to go to the Add Object Type page.
  5. Set Object Type Name to BookInfo, and click Next.
  6. Click +Add Field to add the following fields, and click Next.

    Field

    Type

    Primary Key

    Not Null

    Encrypt

    Default Value

    id

    Integer

    bookName

    String

    author

    String

    price

    Double

    publisher

    String

    publishTime

    Date

    shadowFlag

    Boolean

    true

  7. Click +Add Index, set Index Name to bookName and Indexed Field1 to bookName, and then click Next.
  8. Set the required roles and permissions.
  9. Click OK. The new object type is displayed in the object type list.
  10. Click Export.
  11. Select a file format as prompted. Here, Objective-C is selected.
  12. Click OK. The exported Objective-C file contains all object type information of this version, and will be added to the local development environment in the subsequent step.
  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Cloud DB.
  4. Click the Cloud DB Zones tab.
  5. Click Add to go to the Add Cloud DB Zone page.
  6. Set Cloud DB Zone Name to QuickStartDemo.
  7. Click OK.

Add the exported Objective-C file to the local development environment. If the file already exists, replace it with the exported one. To ensure successful integration, do not modify the exported Objective-C file.

After adding the object type file, you can develop your app using Cloud DB. Before that, you need to initialize AGConnectCloudDB, and create a Cloud DB zone and an object type. You can check the sample code under each of the following steps:

  1. Import AGConnectCore to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
    @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [AGCInstance startUp]; return YES; }
  2. Initialize AGConnectCloudDB in your app.
    [AGConnectCloudDB initEnvironment:&error];
  3. Obtain an AGConnectCloudDB instance and create an object type.
    self.agcConnectCloudDB = [AGConnectCloudDB shareInstance]; [self.agcConnectCloudDB createObjectType:[AGCCloudDBObjectTypeInfoHelper obtainObjectTypeInfo] error:&createError];
  4. Create the Cloud DB zone configuration object, and open the Cloud DB zone.
    NSString *zoneName = @"QuickStartDemo"; AGCCloudDBZoneConfig *zoneConfig = [[AGCCloudDBZoneConfig alloc] initWithZoneName:zoneName syncMode:AGCCloudDBZoneSyncModeCloudCache accessMode:AGCCloudDBZoneAccessModePublic]; zoneConfig.persistence = YES; __weak typeof(self) weakSelf = self; [self.agcConnectCloudDB openCloudDBZone2:zoneConfig allowCreate:YES callback:^(AGCCloudDBZone * _Nullable zone, NSError * _Nullable error) { if (error) { NSLog(@"created cloud database zone failed with reson:%@", error); } else { weakSelf.dbZone = zone; } [self.agcConnectCloudDB enableNetwork:zoneName]; }];

The following describes how to write data in your app using the Cloud DB SDK. When designing UI for your app, you need to create a button for adding data that will be written through executeUpsert. If only one data record is added, you can use the executeUpsertOne method to write it. Sample code:

- (void)executeUpsertWithBook:(BookInfo *__nonnull)book complete:(void (^)(BOOL success, NSError *error))complete { if (book == nil) { return; } if (book.bookName.length == 0) { return; } book.id = @([[self getCurrentTimestamp] integerValue]); [self.dbZone executeUpsertOne:book onCompleted:^(NSInteger count, NSError *_Nullable error) { if (error) { if (complete) { complete(NO, error); } } else { if (complete) { complete(YES, nil); } } }]; }

The app home page needs to display all data when a user signs in to your app. To implement this function, you need to call executeQuery, set the first parameter to [AGCCloudDBQuery where:[BookInfo class]], and pass all queried data through snapshot. Sample code:

- (void)queryAllBooksWithResults:(void (^)(NSArray *bookList, NSError *error))results { AGCCloudDBQuery *query = [AGCCloudDBQuery where:[BookInfo class]]; [self.dbZone executeQuery:query policy:AGCCloudDBQueryPolicyCloud onCompleted:^(AGCCloudDBSnapshot *_Nullable snapshot, NSError *_Nullable error) { if (error) { NSLog(@"query book list failed with reson : %@", error); if (results) { results(nil, error); } } else { NSArray *bookList = snapshot.snapshotObjects; if (results) { results(bookList, nil); } } }]; }
  1. Start Xcode, click the run button to run your app on a mobile phone or simulator, and tap Anonymous Login to sign in to your app.
  2. After successful sign-in, click + to add data.
  3. Enter the book information.
  4. Run your app on another phone, and check the added data.

Well done. You have successfully created an app that integrates Cloud DB of AppGallery Connect, and learned how to build an app that supports device-cloud data synergy using Cloud DB.

API Reference

Sample code

Code copied