Hello
Is there a way to know if the detected finger or face are wrong?
I am using this function:
func authenticate() {
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "We need to unlock your data."
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
DispatchQueue.main.async {
if success {
self.isUnlocked = true
} else {
userPressedCancel = false
}
}
}
} else {
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
I am making a counter app using Core Data to store the value that the user has reached, the problem is that in the DetailView the value changes just if I close the view and reopen it, how can I change the value immediately when the user taps the button?
ContentView:
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@State private var isShown: Bool = false
var body: some View {
NavigationView{
List {
Section(header: Text("All counters")){
ForEach(items) { item in
NavigationLink(
destination:
DetailView(item: item)
.environment(\.managedObjectContext, viewContext)
,
label: {
HStack{
Text(item.name ?? "")
.font(.title3)
.fontWeight(.semibold)
Spacer()
Text("\(item.value, specifier: "%.0f")")
.font(.title3)
.fontWeight(.semibold)
}
})
}
.onDelete(perform: { indexSet in
deleteItems(offsets: indexSet)
print(items)
})
}
}
.listStyle(InsetGroupedListStyle())
.sheet(isPresented: $isShown, content: {
AddView()
.environment(\.managedObjectContext, viewContext)
})
.navigationBarTitle("Counter")
.toolbar {
Menu {
Button(action: {
isShown.toggle()
}) {
Text("Add Item")
}
EditButton()
} label: {
Image(systemName: "plus")
.font(.title)
}
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}
}
DetailView:
struct DetailView: View {
@Environment(\.managedObjectContext) private var viewContext
var item: Item
var body: some View {
VStack(alignment: .center, spacing: nil, content: {
Text("\(item.value, specifier: "%.0f")")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.top)
Spacer()
HStack{
Button(action: {
withAnimation{
item.value += 1
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}, label: {
Image(systemName: "plus")
})
Button(action: {
withAnimation{
item.value -= 1
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}, label: {
Image(systemName: "minus")
})
}
.foregroundColor(.primary)
Spacer()
})
.navigationBarTitle(item.name ?? "", displayMode: .inline)
}
}
Thank you
Hello
I am using matched Geometry Effect to make animations and transitions, the problem is that when I press to start the animation, the object being animated, in this case Text, is duplicated during the transition, and then when I press again to get it back to its original position, no animation takes place, how can I fix it.
Here is the code:
struct ContentView: View {
@StateObject var numberViewModel = NumberViewModel()
@Namespace var animation
var body: some View {
GeometryReader { geo in
NavigationView{
ZStack {
ScrollView{
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
ForEach(numbers){ number in
NumberView(numberViewModel: numberViewModel, animation: animation, number: number)
.onTapGesture {
withAnimation(.easeInOut(duration: 1)){
numberViewModel.selected = number
numberViewModel.tapped = true
}
}
}
}
}
if numberViewModel.tapped{
NumberTappedView(animation: animation, numberViewModel: numberViewModel)
.position(
x: geo.frame(in:.global).midX,
y: geo.frame(in:.global).midY
)
.onTapGesture {
withAnimation(.easeInOut(duration: 1)){
numberViewModel.selected = Number(number: 0)
numberViewModel.tapped = false
}
}
}
}
}
}
}
}
struct NumberView: View {
@ObservedObject var numberViewModel: NumberViewModel
var animation: Namespace.ID
var number: Number
var body: some View{
GroupBox{
if !(numberViewModel.selected.number == number.number){
Text("\(number.number)")
.font(.largeTitle)
.frame(width: 100, height: 100, alignment: .center)
.matchedGeometryEffect(id: number.number, in: animation)
}
}
}
}
struct Number: Identifiable {
var id = UUID()
var number: Int
}
var numbers: [Number] = [
Number(number: 1),
Number(number: 2)
]
struct NumberTappedView: View {
var animation: Namespace.ID
@ObservedObject var numberViewModel: NumberViewModel
var body: some View{
GroupBox{
Text("\(numberViewModel.selected.number)")
.font(.largeTitle)
.frame(width: 200, height: 200, alignment: .center)
.matchedGeometryEffect(id: numberViewModel.selected.number, in: animation)
}
}
}
class NumberViewModel: ObservableObject {
@Published var selected: Number = Number(number: 0)
@Published var tapped: Bool = false
}
Thank You!
Hello
I was trying to use @FetchRequest in a class, but found it doesn't work, so I was wondering if there was a way to use something that works like @FetchRequest in a class?
Thank You!
Hello
@FetchRequest(
entity: Book.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Book.entity.date, ascending: true)]
) var books: FetchedResults<Book.entity>
How can I get notified when anything in book changes without using
.onRecevie(books.publisher){ _ in
....
}
And is there any way to use .onChange modifier with books?
Thank You!
Hello
I am using a SwiftUI @FetchRequest to displays Core Data items, one of the properties of the entity is date, and I want to filter items by today's Date, this is the @FetchRequest:
@FetchRequest(
entity: Book.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Book.date, ascending: true)],
predicate: NSPredicate(format: "date == %@"),
animation: .default)
var books: FetchedResults<Book>
How do I complete the NSPredicate to make it work? (I know that there are no arguments in the predicate yet)
Thank You!
Hello
I am using CoreData in my App and want to save a single Picker value. I could create an entity with an Integer attribute and always edit the first object in the EntityList. But that doesn't sound like a clean solution.
The Picker is placed inside a settings view and has to be synced with iCloud.
Is there a simple way to do this?
Thank You
Hello
I'm trying to schedule a local notification to fire every day, at a specific time, but from tomorrow.
e.g. "Trigger a notification every day at 2 pm, from tomorrow"
This is how I set up my schedule function.
func scheduleNotifications(date: Date, identfier: String, after: Bool) {
let content = UNMutableNotificationContent()
content.title = "App"
content.body = "Test"
content.sound = .default
content.userInfo = ["Hour": Int(hourFormatter.string(from: date)) ?? 0]
let afterDay = Calendar.current.date(byAdding: .day, value: after ? 1 : 0, to: Date())
var components = Calendar.current.dateComponents([.hour, .minute], from: afterDay!)
components.hour = Int(hourFormatter.string(from: date)) ?? 0
components.minute = Int(minuteFormatter.string(from: date)) ?? 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
Hello
I have an app that uses Core Data with CloudKit to store data. When I am in the app (using the app) and create some new data on an other device, the data is fetched in a few seconds and I see it immediately, however if I am not using the app and create some new data on an other device, I have to enter the app and then the data starts fetching, is there a way to fetch data even if I am not using the app.
Here is my core data stack:
import CoreData
import Combine
class PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init() {
container = NSPersistentCloudKitContainer(name: "CoreData")
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "APP_GROUP_NAME")?.appendingPathComponent("CoreData.sqlite") else {
fatalError("Shared file container could not be created.")
}
let storeDescription = NSPersistentStoreDescription(url: fileContainer)
storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
storeDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "Container_Identifier")
container.persistentStoreDescriptions = [storeDescription]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
}
}
Hello
I'm building an indoor geofencing app with iBeacons.
I want to detect each time a user approaches a beacon and the distance and save this data with Core Data only if the distance (proximity) to the iBeacon is close.
I am using Core Location to do this but I am not using the didEnter / didExit functions as they do not provide the distance to the beacon. I am mainly using the didRange function from locationManager to get all the beacons, find the closest one and its distance.
This approach works perfectly while the app is in the foreground. However, the app starts not working properly in the background. If I just change the app, the didRange function stops working, but if I lock the phone and look at the time on the lock screen, it starts working. The problem is not that the app does not work in the background, but that the functions are activated only in specific cases or times, eg. the phone is locked.
I added these properties in the info.plist
Privacy - Location When In Use Usage Description
Privacy - Location Always and When In Use Usage Description
Required background modes:
Location updates
I also added this code:
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
This is how I add a beacon and start monitoring it:
func addBeacon(id: String, major: Int16 = 0, minor: Int16 = 0) {
guard let uuid = UUID(uuidString: id) else { return }
let region = CLBeaconRegion(uuid: uuid, major: CLBeaconMajorValue(major), minor: CLBeaconMinorValue(minor), identifier: id + major.description + minor.description)
region.notifyOnEntry = true
region.notifyOnExit = true
region.notifyEntryStateOnDisplay = true
self.locationManager.startMonitoring(for: region)
resetValues()
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
let beaconRegion = region as! CLBeaconRegion
if state == .inside {
// Start ranging when inside a region.
manager.startRangingBeacons(satisfying: beaconRegion.beaconIdentityConstraint)
} else {
// Stop ranging when not inside a region.
manager.stopRangingBeacons(satisfying: beaconRegion.beaconIdentityConstraint)
}
}
I am also making sure that locationManager.requestAlwaysAuthorization() is always true
Do you have any ideas why it is not always working in the background?
Thanks for your time.
Hello
I am building a study research app that tracks data of different users. The data is saved through Core Data (with relationships) and I was wondering if there was a way to view all the data through CloudKit?
I know I can use public databases with CloudKit in CoreData but was wondering if that would merge all the data of the different users, and if that is the case how would I deal with it?
If that is not possible how would I download all the data in a PDF that the user can send?
Thanks for your help
Hello, how do I fix "Thread 1: "NSFetchRequest could not locate an NSEntityDescription for entity name 'Goal'"
import SwiftUI
import SwiftData
@main
struct Main: App {
@Environment(\.scenePhase) private var scenePhase
@StateObject var statsViewModel = StatsViewModel()
@StateObject var badgeViewModel = BadgeViewModel()
@StateObject var localNotificationManager = LocalNotificationManager()
@AppStorage("notifications") var notificationsSet: Bool = false
@Environment(\.modelContext) private var modelContext
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(statsViewModel)
.environmentObject(badgeViewModel)
.environmentObject(localNotificationManager)
.task {
if !notificationsSet {
do{
try await localNotificationManager.reqeustAuthorization()
await localNotificationManager.setUpNotificationsAtStart()
} catch{
}
}
notificationsSet = true
}
}
.modelContainer(container)
.onChange(of: scenePhase) { _, phase in
if phase == .active{
Task{
await localNotificationManager.getCurrentSettings()
await localNotificationManager.getPendingRequest()
}
} else if phase == .background{
do {
try modelContext.save()
} catch {
print("COULD NOT SAVE WITH SWIFTDATA")
}
}
}
}
}
and
@MainActor
var container: ModelContainer = {
let fileContainer = URL.storeURL(for: "group.Water-Alert-App", databaseName: "CoreData")
let defaultDirectoryURL = NSPersistentContainer.defaultDirectoryURL()
let localSchema = Schema([Reminder.self])
let cloudSchema = Schema([Goal.self, WaterData.self, Container.self])
let localConfiguration = ModelConfiguration("Local", schema: localSchema, url: defaultDirectoryURL.appendingPathComponent("Local.sqlite"))
let cloudConfiguration = ModelConfiguration("Cloud", schema: cloudSchema, url: fileContainer, cloudKitDatabase: .private("iCloud.Water-Alert-App-Offical"))
let container = try! ModelContainer(for: Reminder.self, Goal.self, WaterData.self, Container.self, configurations: localConfiguration, cloudConfiguration)
return container
}()
this is the code that makes the app crash
Thank You
Hello
Why does it give me an error when I pass 'name' at line 3?
struct OtherView: View {
@State private var name: String = ""
@ObservedObject var use = Use(name: name)
var body: some View{
VStack{
}
}
}
class Use: ObservableObject {
@Published var name: String
init(name: String) {
self.name = name
}
}
Thank you
Hello
I implemented the filter function in my ForEach loop, and it works just with the valori property but not with the date property , is there a way to let it filter also the date?
I tried to remove the dateFormatter but it didn't work.
Here is the code
import SwiftUI
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
struct Test4: View {
@State private var text: String = ""
var body: some View {
NavigationView{
if !lifetimes.isEmpty{
List{
Section(header: Text("")){
TextField("Search", text: $text)
}
Section(header: Text("")){
ForEach(lifetimes.filter { text.isEmpty || "\($0)".contains(text) }, id: \.id){ lifetimeInputs in
HStack{
Text("\(lifetimeInputs.valori, specifier: "%.0f")")
Spacer()
Text("\(dateFormatter.string(from: lifetimeInputs.date))")
}
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("All History")
} else{
VStack{
Text("No Data")
.font(.largeTitle)
.fontWeight(.semibold)
.foregroundColor(.secondary)
}
.padding(.bottom)
.navigationTitle("All History")
}
}
}
}
struct LifetimeInputsModel: Identifiable {
var id = UUID()
var valori: Double
var date: Date
}
var lifetimes: [LifetimeInputsModel] = [
LifetimeInputsModel(valori: 300, date: Date()),
LifetimeInputsModel(valori: 200, date: Date() + 86400)
]
Thank you
Hello
I am trying to save some data in the Health App from my app, and it is working, the problem is that when I delete that data (already saved) from my app (using the deleteFromHealthKit function) the data is not deleted from the health app. How can I fix this?
Here is the code:
import SwiftUI
import HealthKit
struct ContentView: View {
init() {
//--------
let healthStore = HKHealthStore()
let allTypes = Set([HKObjectType.quantityType(forIdentifier: .dietaryWater)!])
healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
if !success {
print("success")
}
}
}
func fetchHealthData(date: Date, ml: Double) -> Void {
let healthStore = HKHealthStore()
let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)
let waterConsumed = HKQuantitySample.init(type: quantityType!, quantity: .init(unit: HKUnit.literUnit(with: .milli), doubleValue: ml), start: date, end: date)
healthStore.save(waterConsumed) { success, error in
if (error != nil) {
print("Error: \(String(describing: error))")
}
if success {
print("Saved: \(success)")
}
}
}
@State var water: [Water] = []
@State private var value: Double = 0
func deleteFromHealthKit(date: Date, ml: Double) {
let healthStore = HKHealthStore()
let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)
let waterConsumed = HKQuantitySample.init(type: quantityType!, quantity: .init(unit: HKUnit.literUnit(with: .milli), doubleValue: ml), start: date, end: date)
healthStore.delete(waterConsumed) { success, error in
if (error != nil) {
print("Error: \(String(describing: error))")
}
if success {
print("Saved: \(success)")
}
}
}
var body: some View {
NavigationView{
VStack{
Text("Value: \(value)")
.padding()
HStack{
Text("100 ml")
.onTapGesture {
value = 100
}
Text("200 ml")
.onTapGesture {
value = 200
}
}
Button("Add"){
water.append(Water(value: value, date: Date()))
fetchHealthData(date: Date(), ml: value)
}.disabled(value == 0 ? true : false)
.padding()
List{
ForEach(0..<water.count, id: \.self){ i in
HStack{
Text("\(water[i].value)")
Text("\(water[i].date)")
}
.onTapGesture {
deleteFromHealthKit(date: water[i].date, ml: water[i].value)
water.remove(at: i)
}
}
}
}
}
}
}
struct Water: Identifiable {
var id = UUID()
var value: Double
var date: Date
}
Thank you