I have a Core Data container with two entities, a Category and an Item. The Item can have one Category assigned and the Category can be assigned to many Items.
What I need to do is group the items by category in a list in SwiftUI.
The code below doesn't group all items by category, it only shows one item by category. How can I group all items that have the same category assigned under the same category group?
Core Data Entities
Category
Attributes
name
Relationship
items (Type: To Many)
Item
Attributes
name
Relationship
category (Type: To One)
Swiftui
struct ItemsView: View {
let selectedList:List
@EnvironmentObject private var itemSM: ItemServiceModel
var body: some View {
List {
ForEach(itemSM.items) { item in
Section(header: Text(item.category?.name ?? "")) {
ForEach(itemSM.items.filter { $0.category == item.category }) { filteredItem in
Text("\(filteredItem.name ?? "")")
}
}
}
}
.onAppear{
itemSM.loadItems(forList: selectedList)
}
}
}
Service Item Service Model
class ItemServiceModel: ObservableObject{
let manager: CoreDataManager
@Published var items: [Item] = []
func loadItems(forList list: List){
let request = NSFetchRequest<Item>(entityName: "Item")
let sort = NSSortDescriptor(keyPath: \Item.name, ascending: true)
request.sortDescriptors = [sort]
let filter = NSPredicate(format: "list == %@", list)
request.predicate = filter
do{
items = try manager.context.fetch(request)
}catch let error{
print("Error fetching items. \(error.localizedDescription)")
}
}
}
This is what I see, as you can see, only one Fruits & Vegetables section should exist.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Is there a way to remove or resize the image from the tag in the Picker view?
Picker("", selection: $selectedCategory) {
ForEach(categorySM.categories, id: \.self) { category in
HStack {
if let inputImage = UIImage(data: category.image ?? Data()) {
Image(uiImage: inputImage)
.resizable()
.scaledToFit()
}
Text(category.name ?? "")
}
.tag(category as CategoryItem?)
}
}
.font(.callout)
.pickerStyle(.menu)
As you can see in images 1 and 2 below, the image in the tag from the Beverages category is huge and covers almost the entire screen, it also covers the category name (Beverages). Is there a way to remove or resize the image when displaying it on the tag? Basically to make it look like image #3.
Image Link:
https://i.stack.imgur.com/4XpjI.jpg
I'm currently syncing Core Data with the CloudKit public database using NSPersistentCloudKitContainer. The app starts with an empty Core Data store locally and at the app launch it downloads the data from CloudKit public database to the Core Data store, but this can only be accomplished if the user is logged in, if the user is not logged, no data gets downloaded and I get the error below.
Can the NSPersistentCloudKitContainer mirror the data from the CloudKit public database to the local Core Data even if the user is not logged in? Can someone please confirm this is possible?
The reason for my question is because I was under the impression that the users didn't need to be logged to read data from the public database in CloudKit but I'm not sure this applies to NSPersistentCloudKitContainer when mirroring data. I know I can fetch data directly with CloudKit APIs without the user beign logged but I need to understand if NSPersistentCloudKitContainer should in theory work without the user being logged.
I hope someone from Apple sees this question since I have spent too much time researching without any luck.
Error
Error fetching user record ID: <CKError 0x600000cb1b00: "Not Authenticated" (9); "No iCloud account is configured">
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1192): <NSCloudKitMirroringDelegate: 0x600003b00460>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x10700f0d0> (URL: file:///Users/UserName/...
I'm currently syncing core data with the CloudKit private and public databases, as you can see in the code below, I'm saving the private database in the default configuration in Core Data and the public in a configuration called Public everything works fine when NSPersistentCloudKitContainer syncs, what I'm having an issue with is trying to save to the public data store PublicStore, for instance when I try to save with func createIconImage(imageName: String) it saves the image to the "default" store, not the PublicStore(Public configuration).
What could I do to make the createIconImage() function save to the PublicStore sqlite database?
class CoreDataManager: ObservableObject{
static let instance = CoreDataManager()
private let queue = DispatchQueue(label: "CoreDataManagerQueue")
@AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false
lazy var context: NSManagedObjectContext = {
return container.viewContext
}()
lazy var container: NSPersistentContainer = {
return setupContainer()
}()
init(inMemory: Bool = false){
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
}
func updateCloudKitContainer() {
queue.sync {
container = setupContainer()
}
}
private func getDocumentsDirectory() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
private func getStoreURL(for storeName: String) -> URL {
return getDocumentsDirectory().appendingPathComponent("\(storeName).sqlite")
}
func setupContainer()->NSPersistentContainer{
let container = NSPersistentCloudKitContainer(name: "CoreDataContainer")
let cloudKitContainerIdentifier = "iCloud.com.example.MyAppName"
guard let description = container.persistentStoreDescriptions.first else{
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
if iCloudSync{
if description.cloudKitContainerOptions == nil {
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier)
description.cloudKitContainerOptions = options
}
}else{
print("Turning iCloud Sync OFF... ")
description.cloudKitContainerOptions = nil
}
// Setup public database
let publicDescription = NSPersistentStoreDescription(url: getStoreURL(for: "PublicStore"))
publicDescription.configuration = "Public" // this is the configuration name
if publicDescription.cloudKitContainerOptions == nil {
let publicOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier)
publicOptions.databaseScope = .public
publicDescription.cloudKitContainerOptions = publicOptions
}
container.persistentStoreDescriptions.append(publicDescription)
container.loadPersistentStores { (description, error) in
if let error = error{
print("Error loading Core Data. \(error)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return container
}
func save(){
do{
try context.save()
//print("Saved successfully!")
}catch let error{
print("Error saving Core Data. \(error.localizedDescription)")
}
}
}
class PublicViewModel: ObservableObject {
let manager: CoreDataManager
@Published var publicIcons: [PublicServiceIconImage] = []
init(coreDataManager: CoreDataManager = .instance) {
self.manager = coreDataManager
}
func createIconImage(imageName: String) {
let newImage = PublicServiceIconImage(context: manager.context)
newImage.imageName = imageName
newImage.id = UUID()
save()
}
func save() {
self.manager.save()
}
}
How can I reload the NSPersistentCloudKitContainer from a SwiftUI View?
I have a SwiftUI + MVVM + CloudKit app that successfully syncs to CloudKit but what I would like to be able to do is reload the NSPersistentCloudKitContainer from some View in the app to be able to evaluate if the app should sync to CloudKit or not by setting the cloudKitContainerOptions to nil (description.cloudKitContainerOptions = nil) if the user doesn't want to sync.
In other words, I need to reload the code inside the init() method in the CoreDataManager file when a method in the View Model is called. See the code and comments below.
Here is the code...
Core Data Manager
class CoreDataManager{
static let instance = CoreDataManager()
let container: NSPersistentCloudKitContainer
let context: NSManagedObjectContext
init(){
container = NSPersistentCloudKitContainer(name: "CoreDataContainer")
guard let description = container.persistentStoreDescriptions.first else{
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
/// This is the code that I would like to control from other view in the app
/// if iCloudSync is off, do nothing otherwise set it to nil
if !iCloudSync{
description.cloudKitContainerOptions = nil
}
container.loadPersistentStores { (description, error) in
if let error = error{
print("Error loading Core Data. \(error)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
context = container.viewContext
}
func save(){
do{
try context.save()
print("Saved successfully!")
}catch let error{
print("Error saving Core Data. \(error.localizedDescription)")
}
}
}
View Model
Somehow I would like to be able to have a way to control the reload process in the View Model.
class CarViewModel: ObservableObject{
let manager = CoreDataManager.instance
@Published var cars: [Car] = []
init(){
getCars()
}
func addCar(){}
func getCars(){}
func deleteCar(){}
func save(){
self.manager.save()
}
}
SwiftUI View
Then from a view, I would like to control the reload process through the View Model by calling a method.
struct ContentView: View {
@State private var isSync = false
@StateObject var viewModel = CarViewModel()
var body: some View {
VStack {
Toggle("iCloud Sync", isOn: $isSync)
.toggleStyle(SwitchToggleStyle(tint: .red))
if isSync {
// RELOAD the container, something like this
viewModel.reloadContainer(withSync: true)
}
}
}
}
Any help would be appreciated.
Thanks
Hi,
What would be the best animation method in SwiftUI to reproduce the UIKit animation shown below?
What I need is basically a throwing effect starting from point A and ending at Point B. I don't need any bouncing effects, this is more of an effect to let the user know that something was added from point A to Point B; similar to the effect we get when we add a photo to an album in Photos.
I tried using .rotationEffect() but the animation I get is too circular and with no option to add the point locations. I need a more natural throwing-paper-like animation where you define three points, start, apex and end, see the image below.
Please note that Point A and Point B will be some views on the screen and the throwing object will be a simple SF symbol Image(systemName: "circle.fill").
Any suggestions?
What I have tried in SwiftUI that cannot make it look like a throwing paper animation.
struct KeyframeAnimation: View {
@State private var ascend = false
@State private var ascendDescend = false
@State private var descend = false
var body: some View {
ZStack{
VStack{
ZStack{
Image(systemName: "circle.fill")
.font(.title)
.offset(x: -157)
.foregroundColor(Color.red)
.rotationEffect(.degrees(ascend ? 17: 0))
.rotationEffect(.degrees(ascendDescend ? 145: 0))
.rotationEffect(.degrees(descend ? 18: 0))
.onAppear{
withAnimation(Animation.easeInOut(duration: 0.5)){
self.ascend.toggle()
}
withAnimation(Animation.easeInOut(duration: 1)){
self.ascendDescend.toggle()
}
withAnimation(Animation.easeInOut(duration: 2).delay(8)){
self.descend.toggle()
}
}
}
}
}
}
}
UIKit Animation
This is what I need.
@IBAction func startAnimation(_ sender: Any) {
UIView.animateKeyframes(withDuration: 3.0, delay: 0.0, options: [.calculationModeCubic], animations: {
// start
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1.0/5.0, animations: {
self.myView.center = CGPoint(x: self.pointA.center.x, y: self.pointA.center.y)
})
// apex
UIView.addKeyframe(withRelativeStartTime: 1.0/5.0, relativeDuration: 1.0/5.0, animations: {
self.myView.center = CGPoint(x: self.pointB.center.x - 100, y: self.pointB.center.y - 100)
})
// end
UIView.addKeyframe(withRelativeStartTime: 2.0/5.0, relativeDuration: 1.0/5.0, animations: {
self.myView.center = CGPoint(x: self.pointB.center.x, y: self.pointB.center.y)
})
}
)
}
How can I make the following animation move in a more circular/arc way?
What I need is to be able to animate the red circle in an arc shape, where it goes up and then down forming a curve/arc. Right now the animation looks almost linear with just a little bit of curve, and it doesn't look smooth.
import SwiftUI
struct GeometryEffectTesting: View {
@State private var isOn: Bool = false
var body: some View {
VStack{
ZStack{
Image(systemName: "circle.fill")
.font(.title)
.foregroundColor(.orange)
.animation(.easeOut(duration: 0.3), value: isOn)
Image(systemName: "circle.fill")
.font(.title2)
.foregroundColor(.red)
.modifier(SpecialEffect(isAnimating: isOn))
.animation(.easeOut(duration: 0.3), value: isOn)
.onTapGesture {
self.isOn.toggle()
}
}
}
.padding()
}
}
struct SpecialEffect: GeometryEffect{
private var percentage : CGFloat
private var isAnimating : Bool
init(isAnimating: Bool){
self.percentage = isAnimating ? 1 : 0
self.isAnimating = isAnimating
}
var animatableData: CGFloat{
get{return percentage}
set{percentage = newValue}
}
func effectValue(size: CGSize) -> ProjectionTransform {
let transform: CGAffineTransform
if isAnimating{
transform = Self.transform(forPercent: percentage)
}else{
transform = Self.transform(forPercent: 0)
}
return ProjectionTransform(transform)
}
static func transform(forPercent percent: CGFloat) -> CGAffineTransform {
let xPos: CGFloat = 50
let yPos: CGFloat = 50
let transform: CGAffineTransform
if percent == 0{
transform = .init(translationX: 0, y: 0)
return transform
}else{
if percent < 0.25 {
transform = .init(translationX: percent * xPos, y: -percent * yPos)
} else if percent < 0.5 {
transform = .init(translationX: (percent * xPos) * 2, y: -(percent * yPos) * 2)
} else if percent < 0.75 {
transform = .init(translationX: (percent * xPos) * 3, y: -(percent * yPos) * 2)
} else {
transform = .init(translationX: (percent * xPos) * 4, y: -(percent * yPos) * 2)
}
return transform
}
}
}
Hi, I need to send a user notification when the user enter a
certain location/region. I noticed that there is a UNLocationNotificationTrigger
class to do just this insed the UserNotification framework. I have a little
experience using User Notifications with time intervals but haven’t used the
trigger by location. I have a couple of questions when using UNLocationNotificationTrigger.
1.
When you set a user notification by location,
does that means that the phone will constantly be searching the user’s location,
or the GPS will automatically trigger the notification when the user enters the
designated location without constant searching?
2.
Does UNLocationNotificationTrigger drain the
phones battery?
Thanks
In the following code, I have a LocationManager class which provides the city name of the current location via the @Published property wrapper lastSearchedCity.
Then I have a SearchManagerViewModel class that should be in charge of presenting the city name on SwiftUI views based on some conditions (not currently shown in the code below) via the @Published property wrapper cityName. It properly shows the city name when I call the searchAndSetCity() method from ContentView.swift inside an onAppear modifier.
My issue is that if the user turned Location Services off and turns it back On while he/she is in the ContentView.swift the Text view doesn't update, which is understandable since the searchAndSetCity() method would need to be called again.
How can I call the searchAndSetCity() method located inside the SearchManagerViewModel class every time the locationManagerDidChangeAuthorization(_ manager: CLLocationManager) method is called? I believed this method is called every time the authorization status changes.
LocationManager Class
final class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
@Published var lastSearchedCity = ""
var hasFoundOnePlacemark:Bool = false
func checkIfLocationServicesIsEnabled(){
DispatchQueue.global().async {
if CLLocationManager.locationServicesEnabled(){
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest/// kCLLocationAccuracyBest is the default
self.checkLocationAuthorization()
}else{
// show message: Services desabled!
}
}
}
private func checkLocationAuthorization(){
switch locationManager.authorizationStatus{
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
// show message
case .denied:
// show message
case .authorizedWhenInUse, .authorizedAlways:
/// app is authorized
locationManager.startUpdatingLocation()
default:
break
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
hasFoundOnePlacemark = false
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
if error != nil {
self.locationManager.stopUpdatingLocation()
// show error message
}
if placemarks!.count > 0 {
if !self.hasFoundOnePlacemark{
self.hasFoundOnePlacemark = true
let placemark = placemarks![0]
self.lastSearchedCity = placemark.locality ?? ""
}
self.locationManager.stopUpdatingLocation()
}else{
// no places found
}
})
}
}
SearchManagerViewModel Class
class SearchManagerViewModel: ObservableObject{
@Published var cityName = "" // use this directly in SwifUI views
@ObservedObject private var locationManager = LocationManager()
// Call this directly fron onAppear in SwiftUI views
// This method is more complex than what is shown here. It handles other things like HTTP requests etc.
func searchAndSetCity(){
locationManager.checkIfLocationServicesIsEnabled()
self.cityName = locationManager.lastSearchedCity
}
}
ContentView.swift
struct ContentView: View {
@StateObject private var searchManager = SearchManagerViewModel()
var body: some View {
VStack {
Text(searchManager.cityName)
.font(.callout)
}
.onAppear{
searchManager.searchAndSetCity()
}
}
}
Hi, a Service class where I process all Core Data transactions for a single entity/Object and I often find my self needing to access information from other classes and I was wondering if there was an issue by calling these classes in non-UI related classes.
In the following code I'm calling the dogs array from the DogService class inside the DogHouseService class, and I was wondering if this could be an issue.
Are there any possible issue by calling @Published properties from an ObservableObject class inside other classes?
ObservableObject class
class DogService: ObservableObject{
let manager: CoreDataManager
@Published var dogs: [Dog] = []
init(coreDataManager: CoreDataManager = .instance){
self.manager = coreDataManager
loadDogs()
}
//Adds, Deletes, Updates, etc.
func loadDogs(){
let request = NSFetchRequest<Dog>(entityName: "Dog")
do{
dogs = try manager.context.fetch(request)
}catch let error{
print("Error fetching dogs. \(error.localizedDescription)")
}
}
func save(){
self.manager.save()
}
}
Other Class
class DogHouseService{
let dogService = DogService()
for dog in dogService.dogs{
// do something
}
}
I have the following UIKit animation inside a UIViewRepresentable which works fine, it animates a view in a throwing effect like animation from point A to point B. What I would like to be able to do is, set the start and the end position in ContentView when assigning the animation to a view.
Here is the code...
Static Position Animation
import SwiftUI
struct ContentView: View {
@State private var isAnimating = false
var body: some View {
HStack{
Image(systemName: "circle.fill")
.font(.system(size: 65))
.foregroundColor(.blue)
.throwAnimation(isAnimating: $isAnimating)
.onTapGesture {
isAnimating.toggle()
}
}
}
}
struct ThrowAnimationWrapper<Content: View>: UIViewRepresentable{
@ViewBuilder let content: () -> Content
@Binding var isAnimating: Bool
func makeUIView(context: Context) -> UIView {
UIHostingController(rootView: content()).view
}
func updateUIView(_ uiView: UIView, context: Context) {
if isAnimating{
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, options: [.calculationModeCubic], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {
uiView.center = CGPoint(x: 250, y: 300) // how can I make this dynamic
})
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.9, animations: {
uiView.center = CGPoint(x: 100 + 75, y: 100 - 50 )
uiView.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
})
UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.7, animations: {
uiView.center = CGPoint(x: 100, y: 100)// how can I make this dynamic
uiView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
})
}, completion: { _ in
uiView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
}
}
extension View {
func throwAnimation( isAnimating: Binding<Bool>) -> some View {
modifier(ThrowAnimationViewModifier(isAnimating: isAnimating))
}
}
struct ThrowAnimationViewModifier: ViewModifier {
@Binding var isAnimating: Bool
func body(content: Content) -> some View {
ThrowAnimationWrapper(content: {
content
}, isAnimating: $isAnimating)
}
}
How I would like to be able to call it from ContentView
@State private var isAnimating = false
var body: some View {
HStack{
Image(systemName: "circle.fill")
.font(.system(size: 65))
.foregroundColor(.blue)
.throwAnimation(isAnimating: $isAnimating, startPos:CGPoint(x: 250, y: 300), endPos:CGPoint(x: 100, y: 100))
.onTapGesture {
isAnimating.toggle()
}
}
}
}
How can I modify this code in a way that I can enter the start and end position when assigning to a view?
Thanks!
In the following code, I'm saving and syncing objects in Core Data and CloudKit, everything is working fine, once the user creates some objects, the data starts syncing as soon as the user turns the Toggle switch On in the SettingsView. The issue I'm having is that the data continue syncing even after the switch is turned Off until I kill and relaunch the app. After relaunching the app, the data stops syncing.
Any idea what could I do to make sure that the data stops syncing as soon as the toggle switch is turned off?
Again, everything would work fine if the user would kill and relaunch the app right after turning it off, the data stops syncing.
I thought that by calling carViewModel.updateCloudKitContainer() right after turning it off would do the trick since I'm disabling the CloudKit container by making it nil, description.cloudKitContainerOptions = nil but obviously is not enough.
Core Data Manager
class CoreDataManager{
// Singleton
static let instance = CoreDataManager()
@AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false
static var preview: CoreDataManager = {
// Create preview objects
do {
try viewContext.save()
} catch {
}
return result
}()
lazy var context: NSManagedObjectContext = {
return container.viewContext
}()
lazy var container: NSPersistentContainer = {
return setupContainer()
}()
init(inMemory: Bool = false){
/// for preview purposes only, remove if no previews are needed.
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
}
func setupContainer()->NSPersistentContainer{
print("Assgning persistent container... ")
let container = NSPersistentCloudKitContainer(name: "CoreDataContainer")
guard let description = container.persistentStoreDescriptions.first else{
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
if iCloudSync{
let cloudKitContainerIdentifier = "iCloud.com.sitename.myApp"
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier)
description.cloudKitContainerOptions = options
}else{
description.cloudKitContainerOptions = nil // turn cloud sync off
}
container.loadPersistentStores { (description, error) in
if let error = error{
print("Error loading Core Data. \(error)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return container
}
func save(){
do{
try context.save()
}catch let error{
print("Error saving Core Data. \(error.localizedDescription)")
}
}
}
View Model
class CarViewModel: ObservableObject{
let manager: CoreDataManager
@Published var cars: [Car] = []
init(coreDataManager: CoreDataManager = .instance){
self.manager = coreDataManager
loadCars()
}
func updateCloudKitContainer(){
manager.container = manager.setupContainer()
}
func addCar(model:String, make:String?){
// create car
save()
loadCars()
}
func deleteCar(car: Car){
// delete car
save()
loadCars()
}
func loadCars(){
let request = NSFetchRequest<Car>(entityName: "Car")
let sort = NSSortDescriptor(keyPath: \Car.model, ascending: true)
request.sortDescriptors = [sort]
do{
cars = try manager.context.fetch(request)
}catch let error{
print("Error fetching businesses. \(error.localizedDescription)")
}
}
func save(){
self.manager.save()
}
}
Settings View to Turn ClouldKit ON and OFF
struct SettingsView: View {
@ObservedObject var carViewModel:CarViewModel
@AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false
var body: some View {
VStack{
Toggle(isOn: $iCloudSync){// turns On and Off sync
HStack{
Image(systemName: iCloudSync ? "arrow.counterclockwise.icloud" : "lock.icloud")
.foregroundColor(Color.fsRed)
Text(" iCloud Sync")
}
}
.tint(Color.fsRed)
.onChange(of: iCloudSync){ isSwitchOn in
if isSwitchOn{
iCloudSync = true
carViewModel.updateCloudKitContainer()
}else{
iCloudSync = false // turn Off iCloud Sync
carViewModel.updateCloudKitContainer()
}
}
}
}
}
Display Cars View
struct CarsView: View {
@ObservedObject var carViewModel:CarViewModel
// Capture NOTIFICATION
var didRemoteChange = NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange).receive(on: RunLoop.main)
var body: some View {
NavigationView{
VStack{
List {
ForEach(carViewModel.cars) { car in
HStack{
VStack(alignment:.leading){
Text(car.model ?? "")
.font(.title2)
Text(car.make ?? "")
.font(.callout)
}
}
.swipeActions {
Button( role: .destructive){
deleteCar = car
showDeleteActionSheet = true
}label:{
Label("Delete", systemImage: "trash.fill")
}
}
}
}
.navigationBarTitle("Cars")
.onAppear{
carViewModel.loadCars()
}
// reload cars on NOTIFICATION
.onReceive(self.didRemoteChange){ _ in
carViewModel.loadCars()
}
}
}
}
}
Can someone please help me understand PassthroughSubject and CurrentValueSubject? What I understand so far is that they are subjects where subscribers can listen to changes made to these subjects, but I'm really straggling to understand the following.
I'm I correct by saying that PassthroughSubject or CurrentValueSubject could replace delegation and asynchronous function calls?
Is it possible to delare a subject in Class A and subscribe to listen to those subject changes in Class B and in some other classes or are listeners meant to only be used direclty in SwiftUI structs?
Thanks
I need some help understanding how the public database works in CloudKit. First of all, let me say that I know how to connect and use the private database. In this question I'm not looking for an answer on how to connect to the database at self, only the concept. Here is my confusion. I have a set of images that all users in my app will be using, right now what I'm doing is adding the images directly to the app (an Image Set in Xcode) and then I am pulling them to Core Data and then syncing them to CloudKit. As you can see all images are technically stored in every device using my app and in Core Data/CloudKit, not very efficient. What I would like is to have the images stored in a single place where all uses can pull the images from, in this case CloudKit. I know I can have them somewhere in a private server, but I feel like I would be adding more complexity to my app, so I think using CloudKit is a better option for me. Here is my question.
How do I get the images to CloudKit, do I upload them directly to CloudKit and then read from all devices or do I need to first add them to a device and upload to CloudKit from there?
Thanks!
Hi, I'm trying to understand how TestFlight works since a major update of my app is coming soon. I currently have an app in the app store with a few thousand users, the current app was written in UIKit and I'm now rewriting it in SwiftUI and making major updates such as, moving from Realm to Core Data and allowing iCloudSync etc. I don't have users emails, only from the people who have contacted me with questions so, I was wondering if I could somehow invite users to test the new version without having their emails.
Can someone please describe the typical process when using TestFlight?
Would the following process be considered a good practice?
Add a message in the existing app to invite users by asking for their email so they can join TestFlight at a later date.
Release a new Beta version in TestFlight.
Invite the users who subscribed via the old app.
Release to production after users test it.
Thanks