版本記錄
| 版本號 | 時間 |
|---|---|
| V1.0 | 2022.05.30 星期一 |
前言
數(shù)據(jù)的持久化存儲是移動端不可避免的一個問題,很多時候的業(yè)務(wù)邏輯都需要我們進行本地化存儲解決和完成,我們可以采用很多持久化存儲方案,比如說
plist文件(屬性列表)、preference(偏好設(shè)置)、NSKeyedArchiver(歸檔)、SQLite 3、CoreData,這里基本上我們都用過。這幾種方案各有優(yōu)缺點,其中,CoreData是蘋果極力推薦我們使用的一種方式,我已經(jīng)將它分離出去一個專題進行說明講解。這個專題主要就是針對另外幾種數(shù)據(jù)持久化存儲方案而設(shè)立。
1. 數(shù)據(jù)持久化方案解析(一) —— 一個簡單的基于SQLite持久化方案示例(一)
2. 數(shù)據(jù)持久化方案解析(二) —— 一個簡單的基于SQLite持久化方案示例(二)
3. 數(shù)據(jù)持久化方案解析(三) —— 基于NSCoding的持久化存儲(一)
4. 數(shù)據(jù)持久化方案解析(四) —— 基于NSCoding的持久化存儲(二)
5. 數(shù)據(jù)持久化方案解析(五) —— 基于Realm的持久化存儲(一)
6. 數(shù)據(jù)持久化方案解析(六) —— 基于Realm的持久化存儲(二)
7. 數(shù)據(jù)持久化方案解析(七) —— 基于Realm的持久化存儲(三)
8. 數(shù)據(jù)持久化方案解析(八) —— UIDocument的數(shù)據(jù)存儲(一)
9. 數(shù)據(jù)持久化方案解析(九) —— UIDocument的數(shù)據(jù)存儲(二)
10. 數(shù)據(jù)持久化方案解析(十) —— UIDocument的數(shù)據(jù)存儲(三)
11. 數(shù)據(jù)持久化方案解析(十一) —— 基于Core Data 和 SwiftUI的數(shù)據(jù)存儲示例(一)
12. 數(shù)據(jù)持久化方案解析(十二) —— 基于Core Data 和 SwiftUI的數(shù)據(jù)存儲示例(二)
13. 數(shù)據(jù)持久化方案解析(十三) —— 基于Unit Testing的Core Data測試(一)
14. 數(shù)據(jù)持久化方案解析(十四) —— 基于Unit Testing的Core Data測試(二)
15. 數(shù)據(jù)持久化方案解析(十五) —— 基于Realm和SwiftUI的數(shù)據(jù)持久化簡單示例(一)
16. 數(shù)據(jù)持久化方案解析(十六) —— 基于Realm和SwiftUI的數(shù)據(jù)持久化簡單示例(二)
17. 數(shù)據(jù)持久化方案解析(十七) —— 基于NSPersistentCloudKitContainer的Core Data和CloudKit的集成示例(一)
18. 數(shù)據(jù)持久化方案解析(十八) —— 基于NSPersistentCloudKitContainer的Core Data和CloudKit的集成示例(二)
19. 數(shù)據(jù)持久化方案解析(十九) —— 基于批插入和存儲歷史等高效CoreData使用示例(一)
20. 數(shù)據(jù)持久化方案解析(二十) —— 基于批插入和存儲歷史等高效CoreData使用示例(二)
21. 數(shù)據(jù)持久化方案解析(二十一) —— SwiftUI App中Core Data和CloudKit之間的數(shù)據(jù)共享(一)
源碼
1. Swift
首先看下工程組織結(jié)構(gòu)

下面一起看下源碼
1. CoreDataStack.swift
import CoreData
import CloudKit
final class CoreDataStack: ObservableObject {
static let shared = CoreDataStack()
var ckContainer: CKContainer {
let storeDescription = persistentContainer.persistentStoreDescriptions.first
guard let identifier = storeDescription?.cloudKitContainerOptions?.containerIdentifier else {
fatalError("Unable to get container identifier")
}
return CKContainer(identifier: identifier)
}
var context: NSManagedObjectContext {
persistentContainer.viewContext
}
var privatePersistentStore: NSPersistentStore {
guard let privateStore = _privatePersistentStore else {
fatalError("Private store is not set")
}
return privateStore
}
var sharedPersistentStore: NSPersistentStore {
guard let sharedStore = _sharedPersistentStore else {
fatalError("Shared store is not set")
}
return sharedStore
}
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "MyTravelJournal")
guard let privateStoreDescription = container.persistentStoreDescriptions.first else {
fatalError("Unable to get persistentStoreDescription")
}
let storesURL = privateStoreDescription.url?.deletingLastPathComponent()
privateStoreDescription.url = storesURL?.appendingPathComponent("private.sqlite")
let sharedStoreURL = storesURL?.appendingPathComponent("shared.sqlite")
guard let sharedStoreDescription = privateStoreDescription.copy() as? NSPersistentStoreDescription else {
fatalError("Copying the private store description returned an unexpected value.")
}
sharedStoreDescription.url = sharedStoreURL
guard let containerIdentifier = privateStoreDescription.cloudKitContainerOptions?.containerIdentifier else {
fatalError("Unable to get containerIdentifier")
}
let sharedStoreOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier)
sharedStoreOptions.databaseScope = .shared
sharedStoreDescription.cloudKitContainerOptions = sharedStoreOptions
container.persistentStoreDescriptions.append(sharedStoreDescription)
container.loadPersistentStores { loadedStoreDescription, error in
if let error = error as NSError? {
fatalError("Failed to load persistent stores: \(error)")
} else if let cloudKitContainerOptions = loadedStoreDescription.cloudKitContainerOptions {
guard let loadedStoreDescritionURL = loadedStoreDescription.url else {
return
}
if cloudKitContainerOptions.databaseScope == .private {
let privateStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescritionURL)
self._privatePersistentStore = privateStore
} else if cloudKitContainerOptions.databaseScope == .shared {
let sharedStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescritionURL)
self._sharedPersistentStore = sharedStore
}
}
}
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
fatalError("Failed to pin viewContext to the current generation: \(error)")
}
return container
}()
private var _privatePersistentStore: NSPersistentStore?
private var _sharedPersistentStore: NSPersistentStore?
private init() {}
}
// MARK: Save or delete from Core Data
extension CoreDataStack {
func save() {
if context.hasChanges {
do {
try context.save()
} catch {
print("ViewContext save error: \(error)")
}
}
}
func delete(_ destination: Destination) {
context.perform {
self.context.delete(destination)
self.save()
}
}
}
// MARK: Share a record from Core Data
extension CoreDataStack {
func isShared(object: NSManagedObject) -> Bool {
isShared(objectID: object.objectID)
}
func canEdit(object: NSManagedObject) -> Bool {
return persistentContainer.canUpdateRecord(forManagedObjectWith: object.objectID)
}
func canDelete(object: NSManagedObject) -> Bool {
return persistentContainer.canDeleteRecord(forManagedObjectWith: object.objectID)
}
func isOwner(object: NSManagedObject) -> Bool {
guard isShared(object: object) else { return false }
guard let share = try? persistentContainer.fetchShares(matching: [object.objectID])[object.objectID] else {
print("Get ckshare error")
return false
}
if let currentUser = share.currentUserParticipant, currentUser == share.owner {
return true
}
return false
}
func getShare(_ destination: Destination) -> CKShare? {
guard isShared(object: destination) else { return nil }
guard let shareDictionary = try? persistentContainer.fetchShares(matching: [destination.objectID]),
let share = shareDictionary[destination.objectID] else {
print("Unable to get CKShare")
return nil
}
share[CKShare.SystemFieldKey.title] = destination.caption
return share
}
private func isShared(objectID: NSManagedObjectID) -> Bool {
var isShared = false
if let persistentStore = objectID.persistentStore {
if persistentStore == sharedPersistentStore {
isShared = true
} else {
let container = persistentContainer
do {
let shares = try container.fetchShares(matching: [objectID])
if shares.first != nil {
isShared = true
}
} catch {
print("Failed to fetch share for \(objectID): \(error)")
}
}
}
return isShared
}
}
2. CloudSharingController.swift
import CloudKit
import SwiftUI
struct CloudSharingView: UIViewControllerRepresentable {
let share: CKShare
let container: CKContainer
let destination: Destination
func makeCoordinator() -> CloudSharingCoordinator {
CloudSharingCoordinator(destination: destination)
}
func makeUIViewController(context: Context) -> UICloudSharingController {
share[CKShare.SystemFieldKey.title] = destination.caption
let controller = UICloudSharingController(share: share, container: container)
controller.modalPresentationStyle = .formSheet
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: UICloudSharingController, context: Context) {
}
}
final class CloudSharingCoordinator: NSObject, UICloudSharingControllerDelegate {
let stack = CoreDataStack.shared
let destination: Destination
init(destination: Destination) {
self.destination = destination
}
func itemTitle(for csc: UICloudSharingController) -> String? {
destination.caption
}
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: destination) {
stack.delete(destination)
}
}
}
3. AddDestinationView.swift
import SwiftUI
struct AddDestinationView: View {
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var managedObjectContext
@State private var caption: String = ""
@State private var details: String = ""
@State private var inputImage: UIImage?
@State private var image: Image?
@State private var showingImagePicker = false
private var stack = CoreDataStack.shared
var body: some View {
NavigationView {
Form {
Section {
TextField("Caption", text: $caption)
} footer: {
Text("Caption is required")
.font(.caption)
.foregroundColor(caption.isBlank ? .red : .clear)
}
Section {
TextEditor(text: $details)
} header: {
Text("Description")
} footer: {
Text("Description is required")
.font(.caption)
.foregroundColor(details.isBlank ? .red : .clear)
}
Section {
if image == nil {
Button {
self.showingImagePicker = true
} label: {
Text("Add a photo")
}
}
image?
.resizable()
.scaledToFit()
} footer: {
Text("Photo is required")
.font(.caption)
.foregroundColor(image == nil ? .red : .clear)
}
Section {
Button {
createNewDestination()
presentationMode.wrappedValue.dismiss()
} label: {
Text("Save")
}
.disabled(caption.isBlank || details.isBlank || image == nil)
}
}
.sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
ImagePicker(image: $inputImage)
}
.navigationTitle("Add Destination")
}
}
}
// MARK: Loading image and creating a new destination
extension AddDestinationView {
private func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}
private func createNewDestination() {
let destination = Destination(context: managedObjectContext)
destination.id = UUID()
destination.createdAt = Date.now
destination.caption = caption
destination.details = details
let imageData = inputImage?.jpegData(compressionQuality: 0.8)
destination.image = imageData
stack.save()
}
}
struct AddDestinationView_Previews: PreviewProvider {
static var previews: some View {
AddDestinationView()
}
}
4. HomeView.swift
import SwiftUI
struct HomeView: View {
@State private var showAddDestinationSheet = false
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(sortDescriptors: [SortDescriptor(\.createdAt, order: .reverse)])
var destinations: FetchedResults<Destination>
private let stack = CoreDataStack.shared
var body: some View {
NavigationView {
// swiftlint:disable trailing_closure
VStack {
List {
ForEach(destinations, id: \.objectID) { destination in
NavigationLink(destination: DestinationDetailView(destination: destination)) {
VStack(alignment: .leading) {
Image(uiImage: UIImage(data: destination.image ?? Data()) ?? UIImage())
.resizable()
.scaledToFill()
Text(destination.caption)
.font(.title3)
.foregroundColor(.primary)
Text(destination.details)
.font(.callout)
.foregroundColor(.secondary)
.multilineTextAlignment(.leading)
if stack.isShared(object: destination) {
Image(systemName: "person.3.fill")
.resizable()
.scaledToFit()
.frame(width: 30)
}
}
}
.swipeActions(edge: .trailing, allowsFullSwipe: false) {
Button(role: .destructive) {
stack.delete(destination)
} label: {
Label("Delete", systemImage: "trash")
}
.disabled(!stack.canDelete(object: destination))
}
}
}
Spacer()
Button {
showAddDestinationSheet.toggle()
} label: {
Text("Add Destination")
}
.buttonStyle(.borderedProminent)
.padding(.bottom, 8)
}
.emptyState(destinations.isEmpty, emptyContent: {
VStack {
Text("No destinations quite yet")
.font(.headline)
Button {
showAddDestinationSheet.toggle()
} label: {
Text("Add Destination")
}
.buttonStyle(.borderedProminent)
}
})
.sheet(isPresented: $showAddDestinationSheet, content: {
AddDestinationView()
})
.navigationTitle("My Travel Journal")
.navigationViewStyle(.stack)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
// MARK: Custom view modifier
extension View {
func emptyState<EmptyContent>(_ isEmpty: Bool, emptyContent: @escaping () -> EmptyContent) -> some View where EmptyContent: View {
modifier(EmptyStateViewModifier(isEmpty: isEmpty, emptyContent: emptyContent))
}
}
struct EmptyStateViewModifier<EmptyContent>: ViewModifier where EmptyContent: View {
var isEmpty: Bool
let emptyContent: () -> EmptyContent
func body(content: Content) -> some View {
if isEmpty {
emptyContent()
} else {
content
}
}
}
5. ImagePicker.swift
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
6. DestinationDetailView.swift
import CloudKit
import SwiftUI
struct DestinationDetailView: View {
@ObservedObject var destination: Destination
@State private var share: CKShare?
@State private var showShareSheet = false
@State private var showEditSheet = false
private let stack = CoreDataStack.shared
var body: some View {
// swiftlint:disable trailing_closure
List {
Section {
VStack(alignment: .leading, spacing: 4) {
if let imageData = destination.image, let image = UIImage(data: imageData) {
Image(uiImage: image)
.resizable()
.scaledToFit()
}
Text(destination.caption)
.font(.headline)
Text(destination.details)
.font(.subheadline)
Text(destination.createdAt.formatted(date: .abbreviated, time: .shortened))
.font(.footnote)
.foregroundColor(.secondary)
.padding(.bottom, 8)
}
}
Section {
if let share = share {
ForEach(share.participants, id: \.self) { participant in
VStack(alignment: .leading) {
Text(participant.userIdentity.nameComponents?.formatted(.name(style: .long)) ?? "")
.font(.headline)
Text("Acceptance Status: \(string(for: participant.acceptanceStatus))")
.font(.subheadline)
Text("Role: \(string(for: participant.role))")
.font(.subheadline)
Text("Permissions: \(string(for: participant.permission))")
.font(.subheadline)
}
.padding(.bottom, 8)
}
}
} header: {
Text("Participants")
}
}
.sheet(isPresented: $showShareSheet, content: {
if let share = share {
CloudSharingView(share: share, container: stack.ckContainer, destination: destination)
}
})
.sheet(isPresented: $showEditSheet, content: {
EditDestinationView(destination: destination)
})
.onAppear(perform: {
self.share = stack.getShare(destination)
})
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
showEditSheet.toggle()
} label: {
Text("Edit")
}
.disabled(!stack.canEdit(object: destination))
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
if !stack.isShared(object: destination) {
Task {
await createShare(destination)
}
}
showShareSheet = true
} label: {
Image(systemName: "square.and.arrow.up")
}
}
}
}
}
// MARK: Returns CKShare participant permission, methods and properties to share
extension DestinationDetailView {
private func createShare(_ destination: Destination) async {
do {
let (_, share, _) = try await stack.persistentContainer.share([destination], to: nil)
share[CKShare.SystemFieldKey.title] = destination.caption
self.share = share
} catch {
print("Failed to create share")
}
}
private func string(for permission: CKShare.ParticipantPermission) -> String {
switch permission {
case .unknown:
return "Unknown"
case .none:
return "None"
case .readOnly:
return "Read-Only"
case .readWrite:
return "Read-Write"
@unknown default:
fatalError("A new value added to CKShare.Participant.Permission")
}
}
private func string(for role: CKShare.ParticipantRole) -> String {
switch role {
case .owner:
return "Owner"
case .privateUser:
return "Private User"
case .publicUser:
return "Public User"
case .unknown:
return "Unknown"
@unknown default:
fatalError("A new value added to CKShare.Participant.Role")
}
}
private func string(for acceptanceStatus: CKShare.ParticipantAcceptanceStatus) -> String {
switch acceptanceStatus {
case .accepted:
return "Accepted"
case .removed:
return "Removed"
case .pending:
return "Invited"
case .unknown:
return "Unknown"
@unknown default:
fatalError("A new value added to CKShare.Participant.AcceptanceStatus")
}
}
private var canEdit: Bool {
stack.canEdit(object: destination)
}
}
7. EditDestinationView.swift
import SwiftUI
struct EditDestinationView: View {
let destination: Destination
private var stack = CoreDataStack.shared
private var hasInvalidData: Bool {
return destination.caption.isBlank ||
destination.details.isBlank ||
(destination.caption == captionText && destination.details == detailsText)
}
@State private var captionText: String = ""
@State private var detailsText: String = ""
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var managedObjectContext
init(destination: Destination) {
self.destination = destination
}
var body: some View {
NavigationView {
VStack {
VStack(alignment: .leading) {
Text("Caption")
.font(.caption)
.foregroundColor(.secondary)
TextField(text: $captionText) {}
.textFieldStyle(.roundedBorder)
}
.padding(.bottom, 8)
VStack(alignment: .leading) {
Text("Details")
.font(.caption)
.foregroundColor(.secondary)
TextEditor(text: $detailsText)
}
}
.padding()
.navigationTitle("Edit Destination")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
managedObjectContext.performAndWait {
destination.caption = captionText
destination.details = detailsText
stack.save()
presentationMode.wrappedValue.dismiss()
}
} label: {
Text("Save")
}
.disabled(hasInvalidData)
}
ToolbarItem(placement: .navigationBarLeading) {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
}
}
}
}
.onAppear {
captionText = destination.caption
detailsText = destination.details
}
}
}
// MARK: String
extension String {
var isBlank: Bool {
self.trimmingCharacters(in: .whitespaces).isEmpty
}
}
8. Destination+CoreDataClass.swift
import CoreData
@objc(Destination)
public class Destination: NSManagedObject {
}
9. Destination+CoreDataProperties.swift
import CoreData
// MARK: Fetch request and managed object properties
extension Destination {
@nonobjc
public class func fetchRequest() -> NSFetchRequest<Destination> {
return NSFetchRequest<Destination>(entityName: "Destination")
}
@NSManaged public var caption: String
@NSManaged public var createdAt: Date
@NSManaged public var details: String
@NSManaged public var id: UUID
@NSManaged public var image: Data?
}
// MARK: Identifiable
extension Destination: Identifiable {
}
10. AppMain.swift
import SwiftUI
@main
struct AppMain: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
HomeView()
.environment(\.managedObjectContext, CoreDataStack.shared.context)
}
}
}
11. AppDelegate.swift
import CloudKit
import SwiftUI
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
sceneConfig.delegateClass = SceneDelegate.self
return sceneConfig
}
}
final class SceneDelegate: NSObject, UIWindowSceneDelegate {
func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {
let shareStore = CoreDataStack.shared.sharedPersistentStore
let persistentContainer = CoreDataStack.shared.persistentContainer
persistentContainer.acceptShareInvitations(from: [cloudKitShareMetadata], into: shareStore) { _, error in
if let error = error {
print("acceptShareInvitation error :\(error)")
}
}
}
}
后記
本篇主要講述了使用
SwiftUI App中Core Data和CloudKit之間的數(shù)據(jù)共享,感興趣的給個贊或者關(guān)注~~~
