iOS development-OC-Apple provides you with the backstage: CloudKit Simple to use

Source: Internet
Author: User

First, what is Cloudkit

In mobile development, network request data is used daily, we are accustomed to some user changes in the data server, so that the next request to use. Or the developer sends the edited data to the user via the server. But all of this is built on our app's own server. Some of our development will be difficult without a server, for example, the company does not have a server, it does require you to make a user system, which is obviously a headache, because it is almost impossible to complete the task (some people say, the company will not have a server?) Oh, my company did not AH). However, Apple provides some convenience, although not completely replace the backend, but to a certain extent can solve the data cloud storage needs, yes, that's what this article is about: CloudKit. After each developer uses CloudKit, Apple provides it with a small dashboard as the repository for cloud data, and CloudKit provides a set of APIs for accessing data in dashboard. It's so convenient, ah, there are rice.

For a detailed description of Cloudkit, I suggest you look here.

Second, how to use Cloudkit

Before using it, let's take a look at some of the basic data types for Cloudkit.

CloudKit Base Object Types

There are 7 types of base objects for CloudKit. These object types may be slightly different from similar object types that you know in other programming areas.

  • CKContainer: Containers just like the sandbox the app runs, an app can only access content in its own sandbox and can't access other apps. Containers is the outermost container, with each application having and only one of its own container. (In fact, after a developer-authorized configuration of CloudKit Dashboard, an app can also access the container of other apps.) )

  • CKDatabase: Database, a private database used to store sensitive information, such as the gender age of the user, users can only access their own private database. Apps also have a publicly available database to store public information, such as when you're building a location-based app, then geolocation information should be stored in a public database so that all users can access it.

  • CKRecord: A data record in the database. CloudKit uses the record to store structured data through the K/V structure. For key-value storage, the schema for the current value supports NSString, NSNumber, NSData, NSDate, Cllocation, and Ckreference, Ckasset, and arrays that store the above data types.

  • CKRecordZone: The record does not exist in the database in a fragmented way, they are located in the record zones. Each app has a default record zone, and you can also have a custom record zone.

  • CKRecordIdentifier: Is the unique identity of a record that determines the unique location of the record in the database.

  • CKReference: Reference is much like a referential relationship in an RDBMS. As an example of a geolocation check-in application, where each location can contain a lot of users checking in at that location, there is an inclusive dependency between the location and the sign-in.

  • CKAsset: A resource file, such as a binary file. As an example of a sign-in application, the user may also include a photo when they check in, and the photo will be stored in asset form.

This article is about a simple example of using Cloudkit. If we need to make a storage system for user information.

using the Cloudkit environment configuration

before using Cloudkit, we need to do some configuration in Xcode first. (This article is based on Xcode8)

    1. Find the Icolod option in target-capabilities.

    2. Turn on the control switch for icloud.
    3. In the expanded box, make the following settings

The "CloudKit dashBoard" button in containers can go directly to our storage space on icloud. This is to make sure that the developer account used in the app actually exists. Log in to the developer account after entering the webpage.

This screen will appear when the login is successful:

I have saved some of the data here. It is still very intuitive after it is saved, but I do not see the contents of the stored properties, I am still in the study.

Saving data with Cloudhit

If we need to save a user's account, password, user name, phone number, mailbox, user picture, and other data objects. We create a user's attribute class Userinfomodel.

#import<Foundation/Foundation.h>@interfaceUserinfomodel:nsobject/** Account name*/@property (nonatomic,strong) NSString*useraccout;/** User name*/@property (nonatomic,strong) NSString*UserName;/** User profile picture*/@property (nonatomic,strong) UIImage*Useravtar;/** User Mobile number*/@property (nonatomic,strong) NSString*Userphonenum;/** User Mailbox number*/@property (nonatomic,strong) NSString*UserEmail;/** User Password*/@property (nonatomic,strong) NSString*UserPassword;@end

Before we save the data, we can make an entry as a unique indicator (which is not often modified), for example, we choose the account name here, of course you can choose any other characters, the key is to have the basis for the subsequent search. The next step is to save it.

- (void) Savewithmodel: (userinfomodel*) userinfomodel{//because the account name does not change the account name to do the micro-ID is best.Ckrecordid *postrecordid =[[Ckrecordid alloc]initwithrecordname:userinfomodel.useraccout]; Ckrecord*postrecrod =[[Ckrecord alloc] InitWithRecordType:userInfoModel.userAccout Recordid:postrecordid]; //Package the properties and property values of the user class into a dictionary where the property corresponds to the key property value corresponding to the property in which a column is a picture class, Cloudkit does not support directly to save the picture, but can be converted to NSData, which can be saved. Here the Cloudkit submission only accepts NSString, NSNumber, NSData, Cllocation, and Ckreference, Ckasset and other direct storage, other needsNsmutabledictionary *dic =[[Nsmutabledictionary alloc]init]; Nsmutablearray*proparr = [Self Getallprop:[userinfomodelclass]];//here, use Getallprop to post it below     for(NSString *propinchProparr) {if([[Userinfomodel Valueforkey:prop] Iskindofclass:[uiimageclass]]){        //Picture Special Cases in addition processing if the actual other non-conforming storage also needs to be processedUIImage *image =[Userinfomodel Valueforkey:prop]; Postrecrod[prop]= [NSData datawithdata:uiimagepngrepresentation (image)];//the record can be stored as a dictionary of data}Else{Postrecrod[prop]=[Userinfomodel Valueforkey:prop]; }    }        //user information submitted to the cloud[[[Ckcontainer Defaultcontainer] privateclouddatabase] Saverecord:postrecrod completionhandler:^ (CKRecord * Savedplace, Nserror *error) {        if(savedplace) {DLog (@"%@", Savedplace); Successful printing of stored content}Else{DLog (@"%@", error);        Failed print Error}}]; }
-(Nsmutablearray *) Getallprop: (Class) cls{//get all properties of the current classUnsignedintCount//number of record attributesobjc_property_t *properties = Class_copypropertylist (CLS, &count); //TraverseNsmutablearray *marray =[Nsmutablearray array];  for(inti =0; I < count; i++) {        //objc_property_t Property Typeobjc_property_t property =Properties[i]; //gets the name of the property C-language string        Const Char*cname =Property_getname (property); //Convert to Objective C stringNSString *name =[NSString stringwithcstring:cname encoding:nsutf8stringencoding];    [Marray Addobject:name]; }    returnMarray;}
Querying data using Cloudhit
- (void) Cloudgetuserinfowithuseraccout: (NSString *) Useraccout Succeed: (void(^) (userinfomodel*)) Succeed failed: (void(^) (Nserror *)) failed{Userinfomodel*model =[[Userinfomodel alloc]init]; if(useraccout) {Ckrecordid*postrecordid =[[Ckrecordid alloc]initwithrecordname:useraccout]; [[[Ckcontainer Defaultcontainer] privateclouddatabase] fetchrecordwithid:postrecordid completionHandler:^ (Ckrecord * _nullable record, Nserror *_nullable Error) {            //Handle Errors here            if(Error) {if(Failed) {failed (error); }            }Else{//indicates that the query was successful                if(succeed) {//The data has been saved and converted into a dictionary. DiC assigns the key-value pairs in the dictionary to a class corresponding to a property of the same kind because there is a picture so you need to do a nsdata conversionNsmutablearray *marray = [Self Getallprop:[modelclass]];  for(NSString *propinchMarray) {//This is not the case when the data that is added in the background does not appear without corresponding attributes, but for the sake of insurance. Overriding the Setvale:forundefinedkey method in Userinfomodel                        IDinfo =[record Valueforkey:prop]; if(! [Info Iskindofclass:[nsdataclass]]){                            //[model Setvalue:[dic Valueforkey:prop] forkey:prop];[model Setvalue:record[prop] forkey:prop]; }Else{UIImage*image =[UIImage Imagewithdata:info];                        [Model Setvalue:image Forkey:prop]; }} succeed (model);    Callback gets to the model}}]; }}

Using Cloudhit to delete data
- (void) Clouddeletemodelwithmodel: (Userinfomodel *userinfomodel{//Before also said that at the time of storage, we manipulate the data on the cloud is achieved by the record ID, so the name of the record ID should be an infrequently changed attribute, here is the user's account name Ckrecor did*postrecordid =[[Ckrecordid alloc]initwithrecordname:userinfomodel.useraccout]; [[[Ckcontainer Defaultcontainer] privateclouddatabase] deleterecordwithid:postrecordid completionHandler:^ (Ckrecordid * _nullable RecordID, Nserror *_nullable Error) {        if(!error) {//delete succeeded        }Else{DLog (@"Delete failed%@", Error); Print Error}}];}

The above is the simple use of cloudkit. With this, it can be satisfying to store some relatively simple data.

PS: I also just started to use, found a small problem, a single storage of data can not be too large (size is not tested, probably about 2M bar), or will be prompted to fail. So some of the data is too large, may need to be split, or the picture is too large to be compressed to be stored.

iOS development-OC-Apple provides you with the backstage: CloudKit Simple to use

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.