版本记录
版本号 | 时间 |
---|---|
V1.0 | 2020.11.11 星期三 |
前言
数据的持久化存储是移动端不可避免的一个问题,很多时候的业务逻辑都需要我们进行本地化存储解决和完成,我们可以采用很多持久化存储方案,比如说
plist
文件(属性列表)、preference
(偏好设置)、NSKeyedArchiver
(归档)、SQLite 3
、CoreData
,这里基本上我们都用过。这几种方案各有优缺点,其中,CoreData是苹果极力推荐我们使用的一种方式,我已经将它分离出去一个专题进行说明讲解。这个专题主要就是针对另外几种数据持久化存储方案而设立。
1. 数据持久化方案解析(一) —— 一个简单的基于SQLite持久化方案示例(一)
2. 数据持久化方案解析(二) —— 一个简单的基于SQLite持久化方案示例(二)
3. 数据持久化方案解析(三) —— 基于NSCoding的持久化存储(一)
4. 数据持久化方案解析(四) —— 基于NSCoding的持久化存储(二)
5. 数据持久化方案解析(五) —— 基于Realm的持久化存储(一)
6. 数据持久化方案解析(六) —— 基于Realm的持久化存储(二)
7. 数据持久化方案解析(七) —— 基于Realm的持久化存储(三)
8. 数据持久化方案解析(八) —— UIDocument的数据存储(一)
9. 数据持久化方案解析(九) —— UIDocument的数据存储(二)
10. 数据持久化方案解析(十) —— UIDocument的数据存储(三)
11. 数据持久化方案解析(十一) —— 基于Core Data 和 SwiftUI的数据存储示例(一)
12. 数据持久化方案解析(十二) —— 基于Core Data 和 SwiftUI的数据存储示例(二)
13. 数据持久化方案解析(十三) —— 基于Unit Testing的Core Data测试(一)
14. 数据持久化方案解析(十四) —— 基于Unit Testing的Core Data测试(二)
15. 数据持久化方案解析(十五) —— 基于Realm和SwiftUI的数据持久化简单示例(一)
16. 数据持久化方案解析(十六) —— 基于Realm和SwiftUI的数据持久化简单示例(二)
17. 数据持久化方案解析(十七) —— 基于NSPersistentCloudKitContainer的Core Data和CloudKit的集成示例(一)
开始
1. Swift
首先看下工程组织目录
下面就是源码了
1. AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate { }
2. SceneDelegate.swift
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
private let coreDataStack = CoreDataStack.shared
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let context = coreDataStack.context
let contentView = PlacesListView()
.environment(\.managedObjectContext, context)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneWillResignActive(_ scene: UIScene) {
coreDataStack.saveContext()
}
}
3. CoreDataStack.swift
import CoreData
final class CoreDataStack {
static let shared = CoreDataStack()
var context: NSManagedObjectContext {
persistentContainer.viewContext
}
private lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "PlaceTag")
migrateIfRequired(container.persistentStoreCoordinator)
container.persistentStoreDescriptions.first?.url = CoreDataStack.storeURL
container.loadPersistentStores { _, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
func migrateIfRequired(_ psc: NSPersistentStoreCoordinator) {
if FileManager.default.fileExists(atPath: CoreDataStack.storeURL.path) {
return
}
do {
let store = try psc.addPersistentStore(
ofType: NSSQLiteStoreType,
configurationName: nil,
at: CoreDataStack.storeURL,
options: CoreDataStack.storeOptions)
let newStore = try psc.migratePersistentStore(
store,
to: CoreDataStack.storeURL,
options: [NSPersistentStoreRemoveUbiquitousMetadataOption: true],
withType: NSSQLiteStoreType)
try psc.remove(newStore)
} catch {
print("Error migrating store: \(error)")
}
}
private static let storeOptions: [AnyHashable: Any] = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true,
NSPersistentStoreUbiquitousContentNameKey: "CloudStore"
]
private static var storeURL: URL {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
guard let docURL = urls.last else {
fatalError("Error fetching document directory")
}
let storeURL = docURL.appendingPathComponent("PlaceTag.sqlite")
return storeURL
}
func saveContext() {
context.saveContext()
}
}
4. Place+Extension.swift
import UIKit.UIImage
import CoreData.NSManagedObjectContext
extension Place {
static func create(title: String?, note: String?, image: UIImage?, context: NSManagedObjectContext) {
let newPlace = Place(context: context)
newPlace.id = UUID()
newPlace.title = title?.isEmpty == false ? title : "Untitled"
newPlace.note = note?.isEmpty == false ? note : nil
newPlace.image = image?.pngData()
newPlace.date = Date()
context.saveContext()
}
}
5. NSManagedObjectContext+Extension.swift
import CoreData
extension NSManagedObjectContext {
func saveContext() {
do {
try save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
func delete(_ places: [Place]) {
let request = NSFetchRequest(entityName: "Place")
request.predicate = NSPredicate(format: "id IN %@", places.map { $0.id?.uuidString })
do {
let results = (try fetch(request) as? [Place]) ?? []
results.forEach { delete($0) }
} catch {
print("Failed removing provided objects")
return
}
saveContext()
}
}
6. Data+Extension.swift
import UIKit.UIImage
extension Data {
var uiImage: UIImage? {
return UIImage(data: self)
}
}
7. ImagePicker.swift
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
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()
}
}
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext) {
}
}
8. ActionButtonBackgroundStyle.swift
import SwiftUI
struct ActionButtonBackgroundStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding()
.foregroundColor(.white)
.background(Color.accentColor)
.clipShape(Capsule())
.padding([.horizontal])
.shadow(radius: configuration.isPressed ? 2.0 : 6.0)
.scaleEffect(configuration.isPressed ? 0.95 : 1)
}
}
9. AddPlaceView.swift
import SwiftUI
struct AddPlaceView: View {
@State private var title: String = ""
@State private var note: String = ""
@State private var image: UIImage?
@State private var shouldShowImagePicker = false
@Environment(\.managedObjectContext) private var viewContext
@Environment(\.presentationMode) private var presentationMode
var body: some View {
ZStack(alignment: .bottomTrailing) {
Form {
Section(header: Text("Title")) {
TextField("Insert place title here", text: $title)
.autocapitalization(.words)
}
Section(header: Text("Notes")) {
TextField("Insert notes about the place here", text: $note)
.autocapitalization(.sentences)
}
Section {
Button(
action: {
shouldShowImagePicker.toggle()
},
label: makeImageForChoosePhotosButton
)
}
}
Button(
action: {
Place.create(title: title, note: note, image: image, context: viewContext)
presentationMode.wrappedValue.dismiss()
},
label: {
HStack {
Image(systemName: "square.and.arrow.down.fill")
Text("Save Place")
}
}
)
.buttonStyle(ActionButtonBackgroundStyle())
}
.navigationBarTitle("Add Place")
.sheet(isPresented: $shouldShowImagePicker) {
ImagePicker(image: $image)
}
}
@ViewBuilder
private func makeImageForChoosePhotosButton() -> some View {
image.map {
Image(uiImage: $0)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
}
if image == nil {
HStack {
Spacer()
Image(systemName: "photo.on.rectangle")
Text("Choose Photo")
Spacer()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
}
struct AddPlaceView_Previews: PreviewProvider {
static var previews: some View {
AddPlaceView()
}
}
10. PlacesListView.swift
import SwiftUI
import CoreData
struct PlacesListView: View {
@FetchRequest(entity: Place.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Place.date, ascending: false)])
private var places: FetchedResults
@Environment(\.managedObjectContext) private var viewContext
var body: some View {
NavigationView {
ZStack(alignment: .bottomTrailing) {
List {
ForEach(places, id: \.id) { place in
NavigationLink(destination: makeDetailView(from: place)) {
makeItemView(from: place)
}
}.onDelete(perform: deletePlaces)
}
.listStyle(GroupedListStyle())
.overlay(places.isEmpty ? Text("Add a place using the button below") : nil, alignment: .center)
NavigationLink(destination: AddPlaceView()) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add Place")
}
}
.buttonStyle(ActionButtonBackgroundStyle())
}
.navigationBarTitle("PlaceTag")
}
}
private func makeDetailView(from place: Place) -> PlaceDetailView {
return PlaceDetailView(
title: place.title,
subtitle: place.note,
image: place.image?.uiImage)
}
private func makeItemView(from place: Place) -> PlaceItemView {
return PlaceItemView(
title: place.title,
subtitle: place.note,
image: place.image?.uiImage
)
}
private func deletePlaces(at indices: IndexSet) {
DispatchQueue.main.async {
var result: [Place] = []
for index in indices {
result.append(places[index])
}
viewContext.delete(result)
}
}
}
11. PlaceItemView.swift
import SwiftUI
struct PlaceItemView: View {
let title: String?
let subtitle: String?
let image: UIImage?
var body: some View {
HStack(spacing: 16) {
image.map {
Image(uiImage: $0)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 80, height: 80)
.cornerRadius(4)
.padding(.vertical)
}
VStack(alignment: .leading) {
title.map {
Text($0)
.font(.headline)
}
subtitle.map {
Text($0)
.font(.subheadline)
}
}
}
}
}
struct PlaceItemView_Previews: PreviewProvider {
static var previews: some View {
PlaceItemView(
title: "San Francisco",
subtitle: "Golden gate was awesome",
image: UIImage(systemName: "photo")
)
}
}
12. PlaceDetailView.swift
import SwiftUI
struct PlaceDetailView: View {
let title: String?
let subtitle: String?
let image: UIImage?
var body: some View {
ScrollView {
VStack {
image.map {
Image(uiImage: $0)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(8)
.shadow(radius: 10)
}
title.map {
Text($0)
.font(.largeTitle)
}
subtitle.map {
Text($0)
.font(.title)
.foregroundColor(.secondary)
}
}
.multilineTextAlignment(.center)
.padding()
}
.navigationBarTitle(Text(""), displayMode: .inline)
}
}
struct PlaceDetailView_Previews: PreviewProvider {
static var previews: some View {
PlaceDetailView(
title: "San Francisco",
subtitle: "Golden Gate was awesome",
image: UIImage(systemName: "photo")
)
}
}
后记
本篇主要讲述了基于
NSPersistentCloudKitContainer
的Core Data
和CloudKit
的集成示例,感兴趣的给个赞或者关注~~~