Use of iOS project iCloud and CloudKit Dashboard, icloudcloudkit

Source: Internet
Author: User

Use of iOS project iCloud and CloudKit Dashboard, icloudcloudkit

CloudKit is a cloud data storage service launched by Apple Based on iCloud. It consists of the following two parts:

A gauge web page that is used to manage the record types of public data.

A group of API interfaces used for data transmission between iCloud and devices.

 

I. First, enable the iCloud function on XCode.

1: Go to the Capabilities tab of the target project Targets and enable the about iCloud function. If you select "iCloud Documents ents" or "CloudKit", an image with iCloud is automatically generated. for Containers at the beginning, you need to configure certificate support; CloudKit Dashboard can directly jump to the Web to configure the content about iCloud; and Steps is whether the configuration Steps are successful;

 

 

Ii. how to configure certificates to support the iCloud Function

1: Enter the Identifiers in the Apple certificate management background. There is an iCloud Containers menu.

 

Because the name of the Bundle Identifier in the instance is wjy.com. mobileProject; create an iCloud.wjy.com. the ID value of the MobileProject. It starts with an iCloud container. The bundle id of the app must correspond to that of the iCloud container. The Container name must be unique, this is the global identifier used by Cloudkit to access data. Because the iCloud container name contains the bundle id, the bundle id must also be unique (that is why you need to modify com. raywendrelich. BabiFud ). Bytes

To enable entitlements to work, you need to list the App/bundle ID in the certificate, identifier, and id section of the configuration file of the app. This means that the identified certificate uses the set team id and app id to obtain the id of the iCloud container. If it has been identified in an available developer account, Xcode will automatically complete all this. Unfortunately, this is sometimes not synchronized, and you need to update the ID-use the iCloud function panel to modify the CloudKit container ID. Otherwise, modify the info. plist file or the BabiFud. entitlements file to ensure that the id values is consistent with the bundle id.

2: after creating the above ID, perform the App IDs in Identifiers, find our current App ID, and edit it.

Enable the choice of the iCloud function, and select Include CloudKit support. A warning is displayed, and select Edit on the right to Edit it.

At this time, the created iCloud ID can be selected for binding. After the selection, the outside warning will also be eliminated. After the corresponding description file is generated and installed, the above steps in XCode will also be eliminated;

 

3. Set cloud data

1: There are two ways to enter the CloudKit Dashboard operation. The first method is as described in the first point above. You can directly click CloudKit Dashboard to enter, the other is that there is a corresponding menu in the background of the apple account;

2: Go to the CloudKit Dashboard and you will see the following page:

 

2.1 SCHEMA:

CloudKit container advanced classes: Record Types, Security Roles, and sub‑types. The main class is Record Types;

A Record Type is used to define a separate Record (which can be understood as a data model). It is equivalent to a data storage template and is similar to a database table structure;

2.2 public data and PRIVATE DATA

This is where you save the DATA. developers can view all the shared DATA, but can only view their own private DATA, not the user's private DATA. The pribate data is not displayed here, its structure is the same as that of public data;

User Records Information of the current User;

Default Zone: You can view the details of the data here, which is also used later;

2.3 ADMIN is mainly used to manage permissions of the developer team. I will not describe it too much here;

3: switch back to the Record Type option, click "+" in the upper left corner of the right sidebar, and add a model:

Input Model name: by default, there is only one StringField attribute (this is what we call it now). You can click Add Field... below to Add the attribute list;

You can also select the attribute type, such:

After setting, click Save in the lower-right corner to Save the settings! In this way, a model is created. The storage type of data is as follows:

1. NSData (single bytes)  2. NSDate (date and time)  3. NSNumber (both Int and Double)  4. NSString (or String in Swift)  5. NSArray (list)  6. CKReference (used to create relationships between objects)  7. CLLocation (location)  8. CKAsset (file)  

5: Return to the Default Zone. There is an inverted triangle next to the name in the upper-right corner of the blue area in the middle. Here you can select which model to use (query) for data:

 

6: If you want to save the image field, select Asset.

 

Note: 1 Public Record, 1 Private Record, meaning: The model Note contains a Public data and a Private data. Because the iCloud account I log on to is different from the developer account, this is equivalent to the user account, so the private data is invisible here.

 

Iv. Code-based cloud computing

1: first introduce the CloudKit. framework system framework, and introduce the namespace # import <CloudKit/CloudKit. h>.

2: first, determine whether the iCloud function in the mobile phone is enabled. If there is a value below, it indicates that the iCloud function has been enabled;

id cloudUrl=[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];

This method accepts a parameter, that is, the container ID to be obtained. The so-called container ID, most applications only use one iCloud container, so here we pass in nil, it means to get the first available container by default. This method searches for the iCloud container owned by the current application. If it is found, the URL of the container is returned to prove that the iCloud container of the current application is available. If not, nil is returned, proving that the current application's iCloud is unavailable.

Note: The cloud container and your App file sandbox are stored in two different places in the iOS File System:

File: // private/var/mobile/Library/Mobile % 20 Documents/iCloud ~ Com ~ Xxx ~ Aaa/Documents

App sandbox file path Format file: // var/mobile/Containers/Data/Application/3B4376B3-89B5-3342-8057-3450D4224518/Documents/

It can be seen that this is why two different methods are required for accessing the file path of iCloud and Sandbox.

3: Add a record and give it a fixed recordID, just like the primary key of the data table, which can be used for searching, updating, and deleting;

-(Void) addCloudDataWithPublic :( BOOL) isPublic recordID :( NSString *) recordID name :( NSString *) name password :( NSString *) password {// CloudKit allocates some space for the application, to store data, you must first obtain the bucket. Here we directly obtain the default memory (which can be customized): CKContainer * container = [CKContainer defacontainer]; CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase; // public data} else {database = container. privateCloudDatabase; // hide data} // create a primary key I D. This ID can be used to find CKRecordID * noteId = [[CKRecordID alloc] initWithRecordName: recordID]; // create a CKRecord to save the data CKRecord * noteRecord = [[CKRecord alloc: @ "User" recordID: noteId]; // set data [noteRecord setObject: name forKey: @ "name"]; [noteRecord setObject: password forKey: @ "password"]; // Save the [database saveRecord: noteRecord completionHandler: ^ (CKRecord * _ Nullable record, NSError * _ Nullable er Ror) {if (! Error) {[self showAlertMessage: @ "saved successfully"] ;}}] ;}

4: If you want to save a field with an image, CKAsset is required. Its initialization requires a URL. So here, I first save the image data to the local sandbox to generate a URL, then create CKAsset:

// Add a saved submitted image with an image. CKAsset is required. a url is required for initialization. Here, I first save the image data to the local sandbox to generate a URL, then create CKAsset:-(void) saveImageDataWithPublic :( BOOL) isPublic recordID :( NSString *) recordID name :( NSString *) name password :( NSString *) password {// you need CKAsset to save the image. The initialization requires a URL. So here, I first save the image data to the local sandbox to generate a URL, then create CKAsset: UIImage * image = [UIImage imageNamed: @ "icloudImage"]; NSData * imageData = UIImagePNGRepresentation (image); if (ImageData = nil) {imageData = UIImageJPEGRepresentation (image, 0.6);} NSString * tempPath = [NSHomeDirectory () stringByAppendingPathComponent: @ "Documents/imagesTemp"]; NSFileManager * manager = [NSFileManager defaultManager]; if (! [Manager fileExistsAtPath: tempPath]) {[manager createDirectoryAtPath: tempPath withIntermediateDirectories: YES attributes: nil error: nil];} NSString * filePath = [NSString stringWithFormat: @ "% @/% @", tempPath, @ "iCloudImage"]; NSURL * url = [NSURL fileURLWithPath: filePath]; [imageData writeToURL: url atomically: YES]; CKAsset * asset = [[CKAsset alloc] initWithFileURL: url]; // interact with iCloud CKContainer * contai Ner = [CKContainer defaultiner]; CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase; // public data} else {database = container. privateCloudDatabase; // hide data} // you can use CKRecordID * noteId = [[CKRecordID alloc] initWithRecordName: recordID] to create a primary key ID. // create a CKRecord and save the data CKRecord * noteRecord = [[CKRecord alloc] initWithRecordType: @ "User" recordID: noteId]; // set the data [noteRecord setObjec T: name forKey: @ "name"]; [noteRecord setObject: password forKey: @ "password"]; [noteRecord setObject: asset forKey: @ "userImage"]; // save [database saveRecord: noteRecord completionHandler: ^ (CKRecord * _ Nullable record, NSError * _ Nullable error) {if (! Error) {[self showAlertMessage: @ "saved successfully"] ;}}] ;}

5: Find a single record by using recordID

// Search for a single record-(void) Example :( NSString *) recordID withFormPublic :( BOOL) isPublic {// obtain the specified ID CKRecordID * noteId = [[CKRecordID alloc] initWithRecordName: recordID]; // obtain the container CKContainer * container = [CKContainer defaultiner]; // whether the data type is public or private CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase;} else {database = container. privateCloudDatabase;} _ weak typeof (self) weakSelf = self; // query operation [database fetchRecordWithID: noteId completionHandler: ^ (CKRecord * _ Nullable record, NSError * _ Nullable error) {NSString * message = [NSString stringWithFormat: @ "get data with RecordID % @: % @, % @", recordID, [record objectForKey: @ "name"], [record objectForKey: @ "password"]; [weakSelf showAlertMessage: message] ;}];}

6: Query multiple records using the predicates

// Search multiple records (which can be performed using predicates)-(void) searchRecordWithFormPublic :( BOOL) isPublic withRecordTypeName :( NSString *) recordTypeName {CKContainer * container = [CKContainer defacontainer iner]; // whether the data obtained is public or private CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase;} else {database = container. privateCloudDatabase;} NSPredicate * predicate = [NSPredicate failed: YES]; CKQuery * query = [[CKQuery alloc] failed: recordTypeName predicate: predicate]; _ weak typeof (self) weakSelf = self; [database into mquery: query inZoneWithID: nil completionHandler: ^ (NSArray <CKRecord *> * _ Nullable results, NSError * _ Nullable error) {[weakSelf showAlertMessage: [NSString stringWithFormat: @ "% @", results] ;}];}

7: to update a record, you first need to find the record and then modify it. If the corresponding key value exists, modify its value, if the key value does not exist, a new type field is added;

// To update a record, first search for this record and then modify it-(void) updateRecordWithFormPublic :( BOOL) isPublic withRecordTypeName :( NSString *) recordTypeName withRecordID :( NSString *) recordID {// obtain the specified ID CKRecordID * noteId = [[CKRecordID alloc] initWithRecordName: recordID]; // obtain the container CKContainer * container = [CKContainer ultultiner]; // whether the data obtained is public or private CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase;} else {Database = container. privateCloudDatabase;} _ weak typeof (self) weakSelf = self; // query operation [database fetchRecordWithID: noteId completionHandler: ^ (CKRecord * _ Nullable record, NSError * _ Nullable error) {if (! Error) {// modify the original key value [record setObject: @ "aa123456789" forKey: @ "password"]; // if the key does not exist, a [record setObject: @ "male" forKey: @ "gender"]; [database saveRecord: record completionHandler: ^ (CKRecord * _ Nullable record, NSError * _ Nullable error) {if (! Error) {[weakSelf showAlertMessage: @ "modified and saved"];} else {[weakSelf showAlertMessage: [NSString stringWithFormat: @ "error: % @", error] ;}}] ;}}] ;}}

8: delete a record

// Delete record-(void) Upload :( BOOL) isPublic withRecordID :( NSString *) recordID {// obtain the specified ID CKRecordID * noteId = [[CKRecordID alloc] upload: recordID]; // obtain the container CKContainer * container = [CKContainer defacontainer]; // whether the data type is public or private CKDatabase * database; if (isPublic) {database = container. publicCloudDatabase;} else {database = container. privateCloudDatabase;} _ weak typeof (self) weak Self = self; [database deleteRecordWithID: noteId completionHandler: ^ (CKRecordID * _ Nullable recordID, NSError * _ Nullable error) {if (! Error) {[weakSelf showAlertMessage: @ "deleted successfully"]; return;} [weakSelf showAlertMessage: [NSString stringWithFormat: @ "deletion failed % @", error];}

V. Operating instances

Write an instance for login-free on the same mobile phone. The main principle is to get the unique code of the mobile phone device and save it to the cloud through iCloud, after deleting the APP and installing it, You can directly obtain the user and password from the cloud. This instance will be continuously improved. If you are interested, the file synchronization function of iCloud will be compiled. Note that the certificate can be changed to its own. The steps are as follows:

Source code: https://github.com/wujunyang/iCloudProject

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.