Search code examples
iosxcodecloudkitsharingckshare

SwiftUI CKShare Set Default Permission to Read Only


I have a couple of apps that include CloudKit record sharing and it now seems to work ok in iOS 16.

I only include Read Write and Read Only permission options and require the share recipient be in the user contacts.

This does indeed seem to work as expected, however the default choice in the share sheet options is Read Write. The vast majority of the time I want Read Only. I have not been able to find a way to change the default permission from "Can make changes" to "View only"

My CloudSharingController is pretty straightforward:

struct CloudSharingView: UIViewControllerRepresentable {
    let share: CKShare
    let container: CKContainer
    let recipe: Recipe

    func makeCoordinator() -> CloudSharingCoordinator {
        CloudSharingCoordinator(recipe: recipe)
    }

    func makeUIViewController(context: Context) -> UICloudSharingController {
        share[CKShare.SystemFieldKey.title] = recipe.rName
        let controller = UICloudSharingController(share: share, container: container)
        controller.modalPresentationStyle = .formSheet
        controller.delegate = context.coordinator

        controller.availablePermissions = [.allowReadWrite, .allowReadOnly]
        return controller
    }

    func updateUIViewController(_ uiViewController: UICloudSharingController, context: Context) {
    }
}//cloud sharing view

final class CloudSharingCoordinator: NSObject, UICloudSharingControllerDelegate {
    let stack = CoreDataStack.shared
    let recipe: Recipe
    init(recipe: Recipe) {
        self.recipe = recipe
    }

    func itemTitle(for csc: UICloudSharingController) -> String? {
        recipe.rName
    }

    func cloudSharingController(_ csc: UICloudSharingController, failedToSaveShareWithError error: Error) {
        print("Failed to save share: \(error)")
    }

    func cloudSharingControllerDidSaveShare(_ csc: UICloudSharingController) {
        print("Saved the share")
    }

    func cloudSharingControllerDidStopSharing(_ csc: UICloudSharingController) {
        if !stack.isOwner(object: recipe) {
            stack.delete(recipe)
        }
    }
}//cloud sharing coordinator

The screen:

enter image description here

Any guidance would be appreciated. Xcode 14.0, iOS 16.0


Solution

  • The availablePermissions seems to have two pairs of options:

    allowPrivate
    allowPublic
    

    and

    allowReadOnly
    allowReadWrite
    

    You need to specify one from each pair, so in your case it looks like you need

    controller.availablePermissions = [.allowPrivate, .allowReadWrite]
    

    If you don't specify one from a pair, it looks like it takes the most permissive option.