The articles

Look for similar pictures in IOS albums, NSNotification and class objects, instance objects

Introduction to iCloud storage

The iCloud cloud storage is divided into three chunks, namely, key-value, Documents and cloudKit. Each app has its own independent storage space, which can only be found in the Settings of iPhone. If the app is deleted, the corresponding storage space will not be deleted by itself. You need to find it in the iPhone Settings and delete it. Similar to the remote sandbox system.

Icloud-key-value is only good for storing small data, such as user preferences, system Settings, and simple App states. Each App user can store a maximum of 1MB of data. The maximum number of keys is 1024, the maximum length of each key is 64Bytes, and each key can store a maximum of 1MB of value.

CloudKit is similar to an SQL database, and data can be stored into iCloudKit through CoreData.

Let’s focus on today’s protagonist, iCloud Documents storage

iCloud-Documents

The working principle of

The sandbox system and iCloud container are two different areas of the file system in IOS. Unlike the sandbox system, the iCloud container needs to be configured in advance to be used.

  1. First we use prior to apply for a good container ID, call NSFileManager URLForUbiquityContainerIdentifier. Let the system configure the container

  2. After the container is configured, the system gives the operation URL of the file to the app

  3. The app takes the returned URL, builds more urls to specify files and directories, and uses that URL to create metadata queries to search for containers

The transmission step

The file transfer between the iCloud Container and the iCloud cloud is incremental. After the first upload, all subsequent changes are made based on the first uploaded data. Download the same

The first upload of the document

The first step is to send the metadata, including the document name, modification date, size, and file type. This metadata transfer happens very quickly. The second step is to send the document data, which is binary data.

A second upload or modification of the same file (incremental upload).

By storing the document’s data on the server, iCloud will optimize future transfers to and from the device. ICloud does not send an entire file or package every time it is changed, but only metadata and snippets that have changed. Figure 3-3 visually shows this incremental upload. As before, the system sends the file metadata first so iCloud can broadcast it to other devices. After sending metadata, the system uploads only the changed portions of the document. This optimization reduces iCloud Internet traffic and reduces the amount of power consumed by the device. You can help optimize by designing file formats that support incremental transfers, as described in Network Transfer Efficiency Design.

First document download

When a new file appears in iCloud, the file must be downloaded to other devices, as shown in Figure 3-4. For each device, iCloud first sends the document’s metadata so the device knows the file exists. After that, the time to retrieve the file data depends on the type of device. In iOS, the application must ask the system (explicitly or implicitly) to download files. You can try using NSFileCoordinator class method to access the files to the implicit in the download file, also can by calling the startDownloadingUbiquitousItemAtURL: error: method of approach to explicit the downloaded file. NSFileManager class. The Mac automatically downloads files when it detects them on the server. For this reason, macs are sometimes called “greedy peers.” If your Mac application sees metadata for a new document, but the document itself is not yet a local document, the system may have downloaded the document on behalf of your application.

A second download or modification of the same file (an incremental download).

After downloading a file for the first time, download only the changed part of the file, as shown in Figure 3-5. As with all transfers, the first step in the transfer process is to download the updated document metadata for the file. After receiving the metadata, the device automatically extracts the changes at the appropriate time. On iOS devices, changes are made at appropriate times, such as when the application with the file appears in the foreground. In OS X, changes are pulled out immediately

Operation method

UIDocument

role

Applications that use UIDocument and its underlying architecture get a number of benefits from their documents: asynchronously reading and writing data from a background queue. As a result, your application’s responsiveness to users will not be affected during read and write operations. Automatic coordinated read and write of document files integrated with cloud services. Support for finding conflicts between different versions of documents (if they occur). First write the data to a temporary file, then replace the current document file with it to safely save the document data. Timely automatic saving of document data; This mechanism includes support for handling pending behavior. In the model-view-controller design pattern, a UIDocument object is either a model object or a model controller object — it manages the document’s data, or the aggregate model objects that together make up the document’s data. Typically, you can pair it with a view controller that manages the view that renders the contents of the document. UIDocument does not support managing document views. Document-based applications include those that can generate multiple documents, each with its own file system location. A document-based application must create a subclass of UIDocument for its documents. For more information, see Subclassing Comments below.

Method of use

Create a new Document
SaveToURL: forSaveOperation: completionHandler:.Copy the code
Open an existing Document
OpenWithCompletionHandler:Copy the code
Edit the Document

Changes to the document are tracked as the user edits. UIDocument periodically records unsaved changes and writes document data to its file.

Close the Document

Call closeWithCompletionHandler: on the document instance. If there are any unsaved changes, UIDocument is saved.

UIDocument read and write call sequence

Creates or writes a new file

First call the saveToURL method, passing in the path to the save file, and the save method, whether the callback succeeds

[self saveToURL:self.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
        
        block(success);
    }];
Copy the code

It then calls contentsForType to construct, which needs to save the form of the file

- (id) contentsForType:(NSString *)typeName error:(NSError * _Nullable __autoreleasing *)outError 
Copy the code

Finally, the creation is complete

Read a file

Open the file by calling the openWithCompletionHandle method

[doc openWithCompletionHandler:^(BOOL success) {
        
        if (success) {
            NSLog(@" Open successfully");
        } else {
            
            NSLog(@" Failed to open"); }}];Copy the code

Then the loadFromContents method data that triggers a UIDocument will be returned in loadFromContents

- (BOOL) loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError * _Nullable __autoreleasing *)outError
Copy the code

Feature list

Realize the function Relevant methods Introduction to the
Create a new standard document UIDocument Use document objects to create and manage data structures in your document format. The Document class automatically supports saving new documents to an iCloud container or local storage.
Create a CoreData data document UIManagedDocument Use the Core Data document subclass to create and manage your Core Data stores. For more information, see Designing Core Data in iCloud.
Get the URL of the iCloud document NSMetadataQuery In iOS, metadata query objects are used to find and get real-time updated information about iCloud documents
Prompt the user to open the document. Custom UI (iOS)Automatic as part of the document In iOS, your application is directly responsible for providing a selection UI for user documents in a simple, concise manner, and this user interface fits well with the rest of your application design.
Handling version conflicts UIDocument, NSFileVersion (iOS) In iOS, the document detects and notifies you about conflicts. Use NSFileVersion objects (one for each revision of the document) to resolve them as needed.
Move, copy and delete iCloud based documents NSFileCoordinator NSFileManager The NSFileManager class is used to process files on disk, always within the context of the file coordinator object.

Use iCloudDrive to share the application space

The following fields need to be added to the application’s PList file to declare that the container is open and externally accessible

<key>NSUbiquitousContainers</key>
    <dict>
        <key>iCloud.com.example.MyApp</key>
        <dict>
            <key>NSUbiquitousContainerIsDocumentScopePublic</key>
            <true/>
            <key>NSUbiquitousContainerSupportedFolderLevels</key>
            <string>Any</string>
            <key>NSUbiquitousContainerName</key>
            <string>MyApp</string>
        </dict>
    </dict>
Copy the code

Once you’re done, you’ll be able to see an APP’s shared cloud disk directory under the iCloud Drive directory on your local file system.