Issue #937

First, you need to enable iCloud Documents capability. Go to target settings -> Signing & Capabilities -> iCloud ` Screenshot 2023-07-28 at 16 09 14

Then inside your Info.plist, add this with your iCloud identifier and app name

<key>NSUbiquitousContainers</key>
<dict>
    <key>iCloud.com.onmyway133.PastePal</key>
    <dict>
        <key>NSUbiquitousContainerIsDocumentScopePublic</key>
        <true/>
        <key>NSUbiquitousContainerName</key>
        <string>PastePal</string>
        <key>NSUbiquitousContainerSupportedFolderLevels</key>
        <string>Any</string>
    </dict>
</dict>

To access to your iCloud Drive folder, we use FileManager to retrieve the folder.

Returns the URL for the iCloud container associated with the specified identifier and establishes access to that container. If you specify nil for this parameter, this method returns the first container listed in the com.apple.developer.ubiquity-container-identifiers entitlement array.

Note that the ubiquity folder retrievement can take some time

Do not call this method from your app’s main thread. Because this method might take a nontrivial amount of time to set up iCloud and return the requested URL, you should always call it from a secondary thread. To determine if iCloud is available, especially at launch time, check the value of the ubiquityIdentityToken property instead

Here I use EasyStash for easy read and write operations

import Foundation
import EasyStash

actor CloudDriveService {
    static let shared = CloudDriveService()

    private(set) var storage: Storage?

    init() {
        guard
            let containerUrl = FileManager.default
                .url(forUbiquityContainerIdentifier: nil)
        else { return }

        let folderUrl = containerUrl.appendingPathComponent("Documents")
        
        var options = Options()
        options.directoryUrl = folderUrl
        storage = try? Storage(options: options)
    }
}

When I print the folderUrl on macOS, I get

/Users/khoa/Library/Mobile Documents/iCloud.com.onmyway133.PastePal/Documents

on iOS, it will be like this

file:///private/var/mobile/Library/Mobile Documents/iCloud.com.onmyway133.PastePal/Documents

Troubleshoot

  • Remember to appendingPathComponent with a folder name to your iCloud Drive root folder
  • In case you don’t see your app folder in iCloud Drive folder, bump CFBundleVersion
  • If you still don’t use your app in iCloud Drive folder despite all read-write operation works, you can try browsing your ubiquity folder folderUrl using Terminal with ls