### Validate CloudKit Container and Authentication (Swift) Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt This Swift unit test verifies CloudKit container setup and iCloud authentication by attempting to fetch record zones from the private database. It checks for common CloudKit errors like bad container, permission failures, or lack of authentication, providing specific failure messages. ```swift import XCTest import CloudKit @testable import CoreDataSync class CoreDataSyncTests: XCTestCase { func test_CloudKitReadiness() throws { // Access CloudKit container using configured identifier let container = CKContainer(identifier: Config.containerIdentifier) let database = container.privateCloudDatabase let fetchExpectation = expectation(description: "Expect CloudKit fetch to complete") database.fetchAllRecordZones { _, error in if let error = error as? CKError { switch error.code { case .badContainer, .badDatabase: XCTFail("Create or select a CloudKit container in this app target's Signing & Capabilities in Xcode") case .permissionFailure, .notAuthenticated: XCTFail("Simulator or device running this app needs a signed-in iCloud account") default: XCTFail("CKError: (error)") } } fetchExpectation.fulfill() } waitForExpectations(timeout: 10) } } ``` -------------------------------- ### Inject Managed Object Context into SwiftUI App Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt The main entry point for the SwiftUI application, which initializes the persistence controller and injects the managed object context into the environment for use by child views. ```swift import SwiftUI @main struct CoreDataSyncApp: App { private let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } ``` -------------------------------- ### Integrate UIImagePickerController with ImagePicker Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt A SwiftUI wrapper for UIImagePickerController that uses the Coordinator pattern to handle delegate callbacks. It allows users to select images from their photo library and updates a bound state variable. ```swift import Foundation import SwiftUI struct ImagePicker: UIViewControllerRepresentable { @Binding var selectedImage: UIImage? @Environment(\.presentationMode) var presentationMode func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {} func makeUIViewController(context: Context) -> some UIViewController { let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .photoLibrary imagePickerController.delegate = context.coordinator return imagePickerController } func makeCoordinator() -> ImagePicker.Coordinator { Coordinator(parent: self) } final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let parent: ImagePicker init(parent: ImagePicker) { self.parent = parent } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { DispatchQueue.main.async { self.parent.selectedImage = (info[.editedImage] ?? info[.originalImage]) as? UIImage self.parent.presentationMode.wrappedValue.dismiss() } } } } ``` -------------------------------- ### Initialize PersistenceController with NSPersistentCloudKitContainer Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt The PersistenceController manages the Core Data stack. It provides a shared singleton for production and a preview instance for SwiftUI, utilizing NSPersistentCloudKitContainer to enable automatic synchronization with CloudKit. ```swift import CoreData import UIKit struct PersistenceController { static let shared = PersistenceController() static var preview: PersistenceController = { let result = PersistenceController() let viewContext = result.container.viewContext for i in 0 ..< 10 { let newContact = Contact(context: viewContext) newContact.name = "Contact #\(i)" newContact.photo = UIImage(systemName: "multiply.circle.fill") } do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return result }() let container: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "CoreDataSync") container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } } return container }() } ``` -------------------------------- ### Create New Contacts with AddContactView in SwiftUI Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt A modal view that provides a text field for contact names and an image picker for selecting photos. It utilizes SwiftUI state management and environment variables to handle user input and view presentation. ```swift import Foundation import SwiftUI struct AddContactView: View { @Environment(\.presentationMode) var presentationMode @State private var image: UIImage? @State private var isShowingImagePicker: Bool = false @State private var nameInput: String = "" let onAdd: ((String, UIImage?) -> Void)? let onCancel: (() -> Void)? var body: some View { NavigationView { VStack { HStack { contactImage.onTapGesture { self.isShowingImagePicker = true } TextField("Full Name", text: $nameInput) .textContentType(.name) } Spacer() } .padding() .navigationTitle("Add Contact") .sheet(isPresented: $isShowingImagePicker, onDismiss: { isShowingImagePicker = false }) { ImagePicker(selectedImage: $image) } .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel", action: { onCancel?() }) } ToolbarItem(placement: .confirmationAction) { Button("Add", action: { onAdd?(nameInput, image) }) .disabled(nameInput.isEmpty) } } } } var contactImage: some View { if let image = image { return AnyView(Image(uiImage: image) .resizable() .scaledToFill() .frame(width: 64, height: 64, alignment: .center) .clipped()) } else { return AnyView(Image(systemName: "photo") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 64, height: 64, alignment: .center) .foregroundColor(.gray)) } } } ``` -------------------------------- ### Configure App Entitlements for CloudKit Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt An XML-based property list defining the required entitlements for iCloud and CloudKit synchronization. It specifies the container identifiers and enables necessary services like push notifications. ```xml aps-environment development com.apple.developer.icloud-container-identifiers iCloud.com.apple.samples.cloudkit.CoreDataSync com.apple.developer.icloud-services CloudKit ``` -------------------------------- ### Display and Manage Contacts with SwiftUI and Core Data Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt This snippet implements a SwiftUI view that fetches contacts from Core Data, displays them in a list, and provides functionality to add or delete records. It uses the @FetchRequest property wrapper to ensure the UI stays in sync with the underlying data store. ```swift import SwiftUI import CoreData struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Contact.name, ascending: true)], animation: .default) private var contacts: FetchedResults @State private var isShowingAddView = false var body: some View { NavigationView { List { ForEach(contacts) { contact in HStack { if let image = contact.photo { Image(uiImage: image) .resizable() .scaledToFill() .frame(width: 64, height: 64, alignment: .center) .clipped() } else { Image(systemName: "person.circle") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 64, height: 64, alignment: .center) .foregroundColor(.gray) } Text(contact.name ?? "None") } } .onDelete(perform: deleteContacts) } .navigationTitle("Core Data Contacts") .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: { isShowingAddView = true }) { Image(systemName: "plus") } } } } .sheet(isPresented: $isShowingAddView) { AddContactView( onAdd: { name, image in isShowingAddView = false addContact(name: name, photo: image) }, onCancel: { isShowingAddView = false } ) } } private func addContact(name: String, photo: UIImage?) { let newContact = Contact(context: viewContext) newContact.name = name newContact.photo = photo do { try viewContext.save() } catch { fatalError("Error: \(error)") } } private func deleteContacts(offsets: IndexSet) { offsets.map { contacts[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } ``` -------------------------------- ### Define Contact Entity in Core Data Model Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt An XML representation of the Core Data entity definition, showing how to configure attributes and transformable types for CloudKit synchronization. ```xml ``` -------------------------------- ### Configure CloudKit Container Identifier Source: https://context7.com/apple/sample-cloudkit-coredatasync/llms.txt Defines the iCloud container identifier required for linking the Core Data stack to a specific CloudKit container in the Apple Developer portal. ```swift enum Config { static let containerIdentifier = "iCloud.com.apple.samples.cloudkit.CoreDataSync" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.