Post

Replies

Boosts

Views

Activity

DecimalPad Issues SwiftUI
Hello I have two questions: I'm using a decimalpad keyboard and when I use the comma the app doesn't recognise it How do I dismiss the keyboard? I want that in every country the decimals are written with the comma ( , ) (Can you please write the solution if you know it, thank you for your time) Code: import SwiftUI struct BMIView: View {          @State private var height = ""     @State private var weight = ""     @Environment(\.presentationMode) var presentationMode     var inputAfterConvertions: Float {          let hh = Float(height) ?? 0          let ww  = Float(weight) ?? 0          var ris: Float = 0          if hh > 0 && ww > 0{          ris = (ww / (hh * hh)) * 1000             return ris         }            return 0     }          var health: String{          if inputAfterConvertions < 18.49 && inputAfterConvertions > 0 { return ""         }         else if inputAfterConvertions > 18.5 && inputAfterConvertions < 24.99{             return ""         } else if inputAfterConvertions > 25{             return ""         }                  return ""     }     @State var isWriting: Bool = false     var body: some View {         NavigationView{             Form{                 Section(header: Text("Enter your height in cm")){                     TextField("Input",text: $height)                         .keyboardType(.decimalPad)                 }                 Section(header: Text("Enter your Weight in kg")){                     TextField("Input",text: $weight)                         .keyboardType(.decimalPad)                 }                 Section(header: Text("Check result")){                     Text("\(inputAfterConvertions, specifier: "%.2f")")                 }             }             .navigationBarTitle("BMI")             .navigationBarItems(trailing:                                     Button(action: {                                         presentationMode.wrappedValue.dismiss()                                     }) {                                         Image(systemName: "xmark").font(.title).foregroundColor(.blue)                                     }             )         }     } } Thank you very much for your time
3
0
5.4k
Jun ’21
Looping views SwiftUI
Hello Is there a view to loop different views, for example in a ForEach loop Here is what I mean: import SwiftUI struct ContentView: View { &#9;&#9;@State var view1 = false &#9;&#9;@State var view2 = false &#9;&#9;@State var view3 = false &#9;&#9;@State var view4 = false &#9;&#9; &#9;&#9;private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())] &#9;&#9; &#9;&#9; &#9;&#9;var textSize: CGFloat { &#9;&#9;&#9;&#9;if UIDevice.current.userInterfaceIdiom == .pad { &#9;&#9;&#9;&#9;&#9;&#9;return 48 &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;return 23 &#9;&#9;} &#9;&#9; &#9;&#9;var title: CGFloat { &#9;&#9;&#9;&#9;if UIDevice.current.userInterfaceIdiom == .pad { &#9;&#9;&#9;&#9;&#9;&#9;return 60 &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;return 34 &#9;&#9;} &#9;&#9; &#9;&#9;var height: CGFloat { &#9;&#9;&#9;&#9;if UIDevice.current.userInterfaceIdiom == .pad { &#9;&#9;&#9;&#9;&#9;&#9;return 0.15 &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;return 0.15 &#9;&#9;} &#9;&#9; &#9;&#9;var weight: CGFloat { &#9;&#9;&#9;&#9;if UIDevice.current.userInterfaceIdiom == .pad { &#9;&#9;&#9;&#9;&#9;&#9;return 0.44 &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;return 0.43 &#9;&#9;} &#9;&#9; &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;NavigationView{ &#9;&#9;&#9;&#9;&#9;&#9;GeometryReader { geometry in &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;ScrollView(.vertical, showsIndicators: true) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;LazyVGrid(columns: gridItemLayout, spacing: 18){ &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Group{ &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("View1") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.foregroundColor(.black) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.frame(width: geometry.size.width * weight, height: geometry.size.height * height) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.background(Color.white) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onTapGesture { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;view1 = true &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.sheet(isPresented: $view1) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;View1() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("View2") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.foregroundColor(.black) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.frame(width: geometry.size.width * weight, height: geometry.size.height * height) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.background(Color.white) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onTapGesture { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;view2 = true &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.sheet(isPresented: $view2) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;View2() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("View3") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.foregroundColor(.black) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.frame(width: geometry.size.width * weight, height: geometry.size.height * height) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.background(Color.white) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onTapGesture { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;view3 = true &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.sheet(isPresented: $view3) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;View3() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("View4") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.foregroundColor(.black) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.frame(width: geometry.size.width * weight, height: geometry.size.height * height) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.background(Color.white) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onTapGesture { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;view4 = true &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.sheet(isPresented: $view4) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;View4() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;}.padding() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;.navigationTitle("Title") &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;} &#9;&#9;} &#9;&#9; &#9;&#9; } Is there a way to put the 4 views in a loop instead of making four different Text Views(they are different views) Thank your for your time
4
0
4.4k
Mar ’21
Use onChange on FetchedResults/@FetchRequest variable or get notified when the variable changes
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!
1
1
1.1k
Sep ’21
.onDelete resets NSPredicate (Core Data, SwiftUI)
Hello I have a list of data in SwiftUI. The data shown in the list can be saved or deleted by using Core Data. In the @FetchRequest property that I am using to display data, I initialized an NSPredicate and in the view, I gave the possibility to the user to change the value of the predicate so that he can filter data, and that is all working, the problem shows up when I delete data from the list when I do so the predicate becomes nil and I don't know why. Here is the code struct SectionList: View { @FetchRequest( entity: LifetimeInputs.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \LifetimeInputs.date, ascending: true)], predicate: nil ) var lifetimeInputsModel: FetchedResults<LifetimeInputs> @FetchRequest(entity: Limit.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Limit.date, ascending: false)]) var limit: FetchedResults<Limit> @Environment(\.dynamicTypeSize) var dynamicTypeSize var size: CGFloat{ if UIDevice.current.userInterfaceIdiom == .phone { switch dynamicTypeSize { case .xSmall: return 11 case .small: return 13 case .medium: return 15 case .large: return 17 case .xLarge: return 19 case .xxLarge: return 21 case .xxxLarge: return 23 default: return 23 } } else { switch dynamicTypeSize { case .xSmall: return 13 case .small: return 15 case .medium: return 17 case .large: return 19 case .xLarge: return 21 case .xxLarge: return 23 case .xxxLarge: return 25 case .accessibility1: return 27 case .accessibility2: return 29 default: return 29 } } } @StateObject var lifeTimeInputsViewModel = LifeTimeInputsViewModel() @Environment(\.managedObjectContext) private var viewContext var conversion: Double { if !limit.isEmpty{ switch limit.last?.unita { case Unit.ml.rawValue: return 1 case Unit.oz.rawValue: return 29.574 default: return 1 } } return 1 } @State private var wantsToFilter: Bool = false @State private var dateSelected = Date() var body: some View { Section{ HStack{ Text("Filter") Spacer() Image(systemName: wantsToFilter ? "checkmark.circle" : "xmark") .font(.system(size: size + 6)) .foregroundColor(wantsToFilter ? .green : .red) .onTapGesture { wantsToFilter.toggle() if wantsToFilter{ lifetimeInputsModel.nsPredicate = NSPredicate( format: "date >= %@ && date <= %@", Calendar.current.dateInterval(of: .day, for: dateSelected)!.start as CVarArg, Calendar.current.dateInterval(of: .day, for: dateSelected)!.end as CVarArg ) } else{ lifetimeInputsModel.nsPredicate = nil } } } DatePicker("Date", selection: $dateSelected, displayedComponents: .date) } header: { Text("Filter") .font(.system(size: size - 4)) } .onChange(of: dateSelected, perform: { _ in if wantsToFilter{ lifetimeInputsModel.nsPredicate = NSPredicate( format: "date >= %@ && date <= %@", Calendar.current.dateInterval(of: .day, for: dateSelected)!.start as CVarArg, Calendar.current.dateInterval(of: .day, for: dateSelected)!.end as CVarArg ) } }) Section{ ForEach(lifetimeInputsModel){ lifetimeInputs in HStack{ Text("\(lifetimeInputs.valori / conversion, specifier: format(unita: !limit.isEmpty ? limit[limit.count - 1].unita ?? ml : ml)) \(!limit.isEmpty ? limit[limit.count - 1].unita ?? ml: ml)") .font(.system(size: size)) Spacer() Text("\(dateFormatter.string(from: lifetimeInputs.date ?? Date()))") .font(.system(size: size)) } } .onDelete{lifeTimeInputsViewModel.deleteItems(offsets: $0, lifetimeInputsModel: lifetimeInputsModel); } } header: { Text("History \(lifetimeInputsModel.count)".localized()).font(.system(size: size - 4)) } } } Thank You!
3
0
1.5k
Jan ’22
Disable local notifications for one day if user completes a task
Hello How do I disable a notification for a day if it is set within one hour and the user has completed a task. This is my function to set up local notifications: import UserNotifications func scheduleNotifications(date: Date, identfier: String) { let content = UNMutableNotificationContent() content.title = "App name" content.body = "Message." content.sound = .default content.userInfo = ["Hour": timeFormatter.string(from: date)] var dateComponents = DateComponents() dateComponents.hour = Int(hourFormatter.string(from: date)) ?? 0 dateComponents.minute = Int(minuteFormatter.string(from: date)) ?? 0 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) }
0
2
1k
Dec ’21
Sync local notifications with CloudKit?
Hello Is there a way to sync notifications that are created locally, on CloudKit, I am using this function to create notifications and I am saving everything in an array func scheduleNotifications(date: Date, identfier: String) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("Success") } else if let error = error { print(error.localizedDescription) } } let content = UNMutableNotificationContent() content.title = "Notification" content.body = "Notification." content.sound = UNNotificationSound.default var dateComponents = DateComponents() dateComponents.hour = Int(hourFormatter.string(from: date)) ?? 0 print(hourFormatter.string(from: date)) dateComponents.minute = Int(minuteFormatter.string(from: date)) ?? 0 print(minuteFormatter.string(from: date)) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } Thank you
0
0
653
Jun ’21
PersistenceController and CloudKit
Hello I am making a To-Do list app where I use CoreData and CloudKit, the problem is that when I added this line of code container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: fileContainer.appendingPathComponent("MJ.sqlite"))] to the PersistenceController, iCloud syncing stopped working. (I need that line of code in order to permit to extensions to access the CoreData database) Any idea to solve the problem? This is all the PersistenceController code struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentCloudKitContainer init(inMemory: Bool = false) { container = NSPersistentCloudKitContainer(name: "MJ") guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.name") else { fatalError("Shared file container could not be created.") } container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: fileContainer.appendingPathComponent("MJ.sqlite"))] 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 } } Thank you!
3
0
2.5k
Dec ’21
Siri Shortcuts with SwiftUI and Core Data
Hello, I have created a simple SwiftUI app with Core Data and want to be able to add data via the shortcuts app, I have implemented Intents and the IntentHandler class. When I create a shortcut to add data to my app and run it, nothing happens in the app, the list does not refresh, the only way to see the added data is to close the app completely and reopen it. How can I refresh the UI immediately? I will post my Core Data stack and my SwiftUI view. struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentContainer init() { container = NSPersistentContainer(name: "SiriShort") guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.SiriShortcut2")?.appendingPathComponent("SiriShort.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) 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 } } View: import SwiftUI import CoreData import Intents struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @State private var view: Bool = false @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.text, ascending: true)], animation: .default) private var items: FetchedResults<Item> var body: some View { NavigationView { List { ForEach(items) { item in Text(item.text!) } .onDelete(perform: deleteItems) } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { withAnimation { let newItem = Item(context: viewContext) newItem.text = "\(Int.random(in: 0...1000))" do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } makeDonation(text: newItem.text!) } } func makeDonation(text: String) { let intent = MakeUppercaseIntent() intent.text = text intent.unit = "1" intent.suggestedInvocationPhrase = "Add \(text) to app" let interaction = INInteraction(intent: intent, response: nil) interaction.donate { (error) in if error != nil { if let error = error as NSError? { print("Donation failed: %@" + error.localizedDescription) } } else { print("Successfully donated interaction") } } } private func deleteItems(offsets: IndexSet) { withAnimation { offsets.map { items[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } }
4
0
2.2k
Jan ’22
iOS background beacon ranging Core Location
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.
1
1
2.0k
Dec ’22
'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.
Hello I'm trying to detect objects with CreateML, but it gives me this warning that I think is breaking my app: 'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately. The classfier.model is a CreatML model that has some images Have any ideas on how to fix it? import UIKit import AVKit import Vision import CoreML class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { &#9;&#9; &#9;&#9;let identifierLabel: UILabel = { &#9;&#9;&#9;&#9;let label = UILabel() &#9;&#9;&#9;&#9;label.backgroundColor = .white &#9;&#9;&#9;&#9;label.textAlignment = .center &#9;&#9;&#9;&#9;label.translatesAutoresizingMaskIntoConstraints = false &#9;&#9;&#9;&#9;return label &#9;&#9;}() &#9;&#9;override func viewDidLoad() { &#9;&#9;&#9;&#9;super.viewDidLoad() &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;// here is where we start up the camera &#9;&#9;&#9;&#9;// for more details visit: https://www.letsbuildthatapp.com/course_video?id=1252 &#9;&#9;&#9;&#9;let captureSession = AVCaptureSession() &#9;&#9;&#9;&#9;captureSession.sessionPreset = .photo &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;guard let captureDevice = AVCaptureDevice.default(for: .video) else { return } &#9;&#9;&#9;&#9;guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return } &#9;&#9;&#9;&#9;captureSession.addInput(input) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;captureSession.startRunning() &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) &#9;&#9;&#9;&#9;view.layer.addSublayer(previewLayer) &#9;&#9;&#9;&#9;previewLayer.frame = view.frame &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;let dataOutput = AVCaptureVideoDataOutput() &#9;&#9;&#9;&#9;dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) &#9;&#9;&#9;&#9;captureSession.addOutput(dataOutput) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;setupIdentifierConfidenceLabel() &#9;&#9;} &#9;&#9; &#9;&#9;fileprivate func setupIdentifierConfidenceLabel() { &#9;&#9;&#9;&#9;view.addSubview(identifierLabel) &#9;&#9;&#9;&#9;identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true &#9;&#9;&#9;&#9;identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true &#9;&#9;&#9;&#9;identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true &#9;&#9;&#9;&#9;identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true &#9;&#9;} &#9;&#9; &#9;&#9;func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { //&#9;&#9;&#9;&#9;print("Camera was able to capture a frame:", Date()) &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;// !!!Important &#9;&#9;&#9;&#9;// make sure to go download the models at https://developer.apple.com/machine-learning/ scroll to the bottom &#9;&#9;&#9;&#9;guard let model = try? VNCoreMLModel(for: Classfier().model) else { return } &#9;&#9;&#9;&#9;let request = VNCoreMLRequest(model: model) { (finishedReq, err) in &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;//perhaps check the err &#9;&#9;&#9;&#9;&#9;&#9; //&#9;&#9;&#9;&#9;&#9;&#9;print(finishedReq.results) &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;guard let results = finishedReq.results as? [VNClassificationObservation] else { return } &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;guard let firstObservation = results.first else { return } &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;print(firstObservation.identifier, firstObservation.confidence) &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;DispatchQueue.main.async { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)" &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request]) &#9;&#9;} } Thank you for your time
2
1
4.9k
Jan ’21
@AppStorage with Date in SwiftUI
Hello I want to be able to save Date in @AppStorage, and it works however I was wondering what was the difference between these two extensions, which one is better and why? extension Date: RawRepresentable { static var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long return formatter }() public var rawValue: String { Date.dateFormatter.string(from: self) } public init?(rawValue: String) { self = Date.dateFormatter.date(from: rawValue) ?? Date() } } and extension Date: RawRepresentable { private static let formatter = ISO8601DateFormatter() public var rawValue: String { Date.formatter.string(from: self) } public init?(rawValue: String) { self = Date.formatter.date(from: rawValue) ?? Date() } } Thank You!
5
0
6.1k
Dec ’24
Notify when @FetchRequest changes?
Hello @FetchRequest( entity: Book(), sortDescriptors: [] ) var books: FetchedResults<Book> How can I get notified when books changes? I was thinking about putting this... .onReceive(NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave), perform: { _ in}) ... in my main View but this would notify me if anything gets saved and that is not what I want. I want to get notified just if a certain FetchRequest changes (in this case books)? How can I do that? Thank You!
4
1
2.6k
Jan ’23
Convert Coredata PersistenceController to SwiftData container
Hello I have a CoreData PersistenceController and would like to convert it to a SwiftData container. Before converting the whole app to use SwiftData I wanted to know if my conversion is right and preserves old data (in iCloud and local). Here is the code: PersistenceController: import CoreData import SwiftUI import Combine #if os(iOS) || os(macOS) || os(watchOS) import WidgetKit #endif struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentCloudKitContainer init() { let fileContainer = URL.storeURL(for: "group.Water-Alert-App", databaseName: "CoreData") container = NSPersistentCloudKitContainer(name: "CoreData") let defaultDirectoryURL = NSPersistentContainer.defaultDirectoryURL() let localStoreURL = defaultDirectoryURL.appendingPathComponent("Local.sqlite") let localStoreDescription = NSPersistentStoreDescription(url: localStoreURL) localStoreDescription.configuration = "Local" // Create a store description for a CloudKit-backed local store let cloudStoreDescription = NSPersistentStoreDescription(url: fileContainer) cloudStoreDescription.configuration = "Cloud" // Set the container options on the cloud store cloudStoreDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.namel") cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) cloudStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) container.persistentStoreDescriptions = [cloudStoreDescription, localStoreDescription] container.loadPersistentStores{ (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy } func save() { if container.viewContext.hasChanges { do { try container.viewContext.save() } catch { print("COULD NOT SAVE WITH CORE DATA") } } } } ModelContainer: 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 }() Thank you!
0
1
693
Jan ’24