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
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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 {
		@State var view1 = false
		@State var view2 = false
		@State var view3 = false
		@State var view4 = false
		
		private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		
		var textSize: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 48
				}
				return 23
		}
		
		var title: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 60
				}
				return 34
		}
		
		var height: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 0.15
				}
				return 0.15
		}
		
		var weight: CGFloat {
				if UIDevice.current.userInterfaceIdiom == .pad {
						return 0.44
				}
				return 0.43
		}
		
		var body: some View {
				NavigationView{
						GeometryReader { geometry in
								ScrollView(.vertical, showsIndicators: true) {
										LazyVGrid(columns: gridItemLayout, spacing: 18){
												Group{
														Text("View1")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view1 = true
														}
														
														.sheet(isPresented: $view1) {
																View1()
														}
														
														Text("View2")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view2 = true
														}
														
														.sheet(isPresented: $view2) {
																View2()
														}
														
														Text("View3")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view3 = true
														}
														
														.sheet(isPresented: $view3) {
																View3()
														}
														
														Text("View4")
														.foregroundColor(.black)
														.frame(width: geometry.size.width * weight, height: geometry.size.height * height)
														.background(Color.white)
														.onTapGesture {
																view4 = true
														}
														
														.sheet(isPresented: $view4) {
																View4()
														}
														
														
												}
												
										}.padding()
										
								}
								
						}
						.navigationTitle("Title")
						
				}
		}
		
		
}
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
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 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!
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)
}
Hello
I wanted to ask if you know where I can start learning CoreML CreateML and integrate them with SwiftUI (NO UIKit please)
Thank You
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
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!
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)")
}
}
}
}
Hello
What would be the best and most efficient way to save photos and videos using Core Data knowing that they will be synced using CloudKit.
Thanks
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'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 {
		
		let identifierLabel: UILabel = {
				let label = UILabel()
				label.backgroundColor = .white
				label.textAlignment = .center
				label.translatesAutoresizingMaskIntoConstraints = false
				return label
		}()
		override func viewDidLoad() {
				super.viewDidLoad()
				
				// here is where we start up the camera
				// for more details visit: https://www.letsbuildthatapp.com/course_video?id=1252
				let captureSession = AVCaptureSession()
				captureSession.sessionPreset = .photo
				
				guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
				guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
				captureSession.addInput(input)
				
				captureSession.startRunning()
				
				let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
				view.layer.addSublayer(previewLayer)
				previewLayer.frame = view.frame
				
				let dataOutput = AVCaptureVideoDataOutput()
				dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
				captureSession.addOutput(dataOutput)
				
				
				
				setupIdentifierConfidenceLabel()
		}
		
		fileprivate func setupIdentifierConfidenceLabel() {
				view.addSubview(identifierLabel)
				identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true
				identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
				identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
				identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
		}
		
		func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
//				print("Camera was able to capture a frame:", Date())
				
				guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
				
				// !!!Important
				// make sure to go download the models at https://developer.apple.com/machine-learning/ scroll to the bottom
				guard let model = try? VNCoreMLModel(for: Classfier().model) else { return }
				let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
						
						//perhaps check the err
						
//						print(finishedReq.results)
						
						guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
						
						guard let firstObservation = results.first else { return }
						
						print(firstObservation.identifier, firstObservation.confidence)
						
						DispatchQueue.main.async {
								self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)"
						}
						
				}
				
				try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
		}
}
Thank you for your time
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!
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!
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!