I am making app that stores some data into CoreData and than show it in on the Custom Keyboard. I have already made everything to store that data and created Custom Keyboard Extension, but I am not sure how can I get that data in this extension. I did something with apps group but still now not sure what am I doing wrong.
My DataController:
import Foundation
import SwiftUI
import CoreData
class DataController: NSObject, ObservableObject {
let container = NSPersistentContainer(name: "DataModel")
let storeDescription = NSPersistentStoreDescription(url: URL.storeURL(for: "group.zo", databaseName: "DataModel"))
override init() {
container.persistentStoreDescriptions = [storeDescription]
container.loadPersistentStores { description, error in
if let error = error {
print("\(error)")
}
}
}
}
public extension URL {
static func storeURL(for appGroup: String, databaseName: String) -> URL {
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
fatalError("Shared file container could not be created.")
}
return fileContainer.appendingPathComponent("\(databaseName).sqlite")
}
}
My KeyboardViewController:
import UIKit
import SwiftUI
import CoreData
class KeyboardViewController: UIInputViewController {
@IBOutlet var nextKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
let child = UIHostingController(rootView: KeyboardView())
child.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
child.view.backgroundColor = .clear
view.addSubview(child.view)
addChild(child)
}
}
My KeyboardView:
import SwiftUI
struct KeyboardView: View {
@EnvironmentObject var dataController: DataController
@FetchRequest(sortDescriptors: []) var snip: FetchedResults<Snip>
var body: some View {
HStack{
VStack(alignment: .leading){
Text("Your Snips")
.font(.system(size: 18, weight: .bold))
if snip.isEmpty {
Text("error")
}else{
ForEach(snip){ snip in
Button {
print(snip.content ?? "error")
} label: {
Text(snip.name ?? "error")
.background(Color(snip.color ?? ""))
}
}
}
Button {
print("siema")
} label: {
Text("test")
.background(Color.red)
}
Spacer()
}.padding()
Spacer()
}
}
}
Please Help!!!