0

I haven't done much with the changes to SwiftUI concurrency with async await but I have gone through all the documentation and I really don't get what's going on here:

I try to share my CloudKit database with other users, I implemented basically 1:1 what Apple is showing here in the sample code https://github.com/apple/sample-cloudkit-sharing/blob/main/Sharing/Views/ContentView.swift https://github.com/apple/sample-cloudkit-sharing/blob/main/Sharing/Views/CloudSharingView.swift

this is my code

Button("share") {
    Task {
            try await shareObjects()
    }
}
.sheet(isPresented: $isShowingShareView) {
    shareView()
}


@State private var activeShare: CKShare?
@State private var activeContainer: CKContainer?

func shareObjects() async throws {
    
    var objects = Array(viewContext.registeredObjects)
    do {
        let (something, share, container) = try await PersistenceController.shared.container.share(objects, to: nil)
        activeShare = share
        activeContainer = container // here its not nil
        isShowingShareView = true
    }
    catch {
        print(error)
    }
    
}

private func shareView() -> CloudSharingView? {
    guard let share = activeShare, let container = activeContainer else {
        print("its nil") // here share and container are nil
        return nil
    }

    return CloudSharingView(container: container, share: share)
}

The share view should come up in the sheet, but it just comes up empty because share and container are nil when shareView() is called (where it prints its nil). When setting breakpoints I see there is data in there - then not anymore, I suspect some kind of issue where this view just knows nothing about my data but why? I also added @MainActor for the methods just to make sure its really on the main thread, but it is. The share action does work, I can see it in CloudKit Dashboard

Any ideas? Thank you!

breeef
  • 1
  • 1
  • 2
    try using `.sheet(item:ondismiss:content:)`, see: https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:) There are a lot of similar posts/answers on this in SO. – workingdog support Ukraine Aug 16 '22 at 00:52
  • 1
    State doesn’t work with class instances… – cora Aug 16 '22 at 01:19
  • Hey thank you both, yes I tried using the item: way but forgot to mention it, it doesn't work either, crashes the App outright because its nil again - it crashes then on @ main @workingdogsupportUkraine – breeef Aug 16 '22 at 07:44
  • The Views are just structs, there is no class @cora – breeef Aug 16 '22 at 07:45
  • SwiftUI triggers a recompute of the body `valueWillChange`, as a dirty fix try `DispatchQueue.main.asyncAfter(deadline: .now + 1) { self.isShowingShareView = true }` see if it fixes the issue. If yes then refactor your code to use an @StateObject and a custom model to hold your `activeContainer` and `activeShare` – user1046037 Aug 16 '22 at 12:41

0 Answers0