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
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
I noticed that in my app, when I add data (I am using Core Data) the size of the app increases, as expected, the problem occurs when I delete data, the size of the app remains unchanged and sometimes increases, I thought there was an error in the my code and so I created, from scratch, a project for iOS with SwiftUI and Core Data enabled (the default template that Xcode provides) and also with the SwiftUI & Core Data default app the same problem happens.
Is there a way to fix it or is there an explanation for this?
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
I wanted to know why when I print(Date()) the date is printed but two hours before?
Example
If I print(Date()) and the actual date is 2021-09-10 22:33:41 +0000, it prints 2021-09-10 20:33:41 +0000 instead of 2021-09-10 22:33:41 +0000.
Why does this happen?
Thank You!
Hello
I created a custom shape in SwiftUI and I am trying to rotate it around a circle, but it works just on the top part of the circle, can you help me make it rotate exactly around the circle?
(And also can I get the same effect using radians? How?)
Here is the code:
import SwiftUI
struct MyGameView: View {
@State private var degress: Double = 0
let timer = Timer.publish(every: 0.05, on: .main, in: .common).autoconnect()
var body: some View {
VStack{
ZStack{
Circle()
.frame(width: 80)
ZStack{
Circle()
.stroke(lineWidth: 1)
.frame(width: 300)
BallonShape()
.scaledToFit()
.scaleEffect(0.2)
.foregroundColor(.red)
.rotationEffect(.degrees(degress), anchor: .bottom)
.offset(x: 0, y: -170)
}
}
}
.onReceive(timer) { input in
withAnimation(.easeIn(duration: 0.05).speed(10)){
degress += 1
}
}
}
}
struct BallonShape: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2))
path.addCurve(to: CGPoint(x: rect.midX, y: rect.minY), control1: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.minX) / 2, y: rect.minY))
path.addCurve(to: CGPoint(x: rect.midX, y: (rect.maxY + rect.midY) / 2), control1: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY), control2: CGPoint(x: (rect.midX + rect.maxX) / 2, y: rect.minY))
}
}
}
Thank You very much!
Hello
How can I remove the Collapse button that is on the navigationBar in iPadOS?
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
If I have this array:
var objects = [
Object(value: 100, date: Date(), imageTemplate: "30"),
Object(value: 200, date: Date(), imageTemplate: "20"),
Object(value: 400, date: Date() + 84000, imageTemplate: "10")
]
How can I count how many different dates are in the array using NSPredicate?
In this case it should return 2.
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 created a simple SwiftUI app with Core Data and I want to be able to add data via the shortcuts app, I created a shortcut that takes some text as input and returns it in uppercase and when I run the shortcut in the shortcuts app, it works, however when I added an "add" function (to save data in the Core Data database) to the intent handle function, and I run it again nothing is saved in the app, here is the code:
class MakeUppercaseIntentHandler: NSObject, MakeUppercaseIntentHandling {
let persistenceController = PersistenceController()
func handle(intent: MakeUppercaseIntent, completion: @escaping (MakeUppercaseIntentResponse) -> Void) {
if let inputText = intent.text {
let uppercaseText = inputText.uppercased()
completion(MakeUppercaseIntentResponse.success(result: add(text: uppercaseText)))
} else {
completion(MakeUppercaseIntentResponse.failure(error: "The text entred is invalid"))
}
}
func resolveText(for intent: MakeUppercaseIntent, with completion: @escaping (MakeUppercaseTextResolutionResult) -> Void) {
if let text = intent.text, !text.isEmpty {
completion(MakeUppercaseTextResolutionResult.success(with: text))
} else {
completion(MakeUppercaseTextResolutionResult.unsupported(forReason: .noText))
}
}
func add(text: String) -> String{
let newItem = Item(context: persistenceController.container.viewContext)
newItem.text = text
do {
try persistenceController.container.viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return text
}
}
Thank You
Hello
I'm trying to compose a layout using the Layout API.
I have already written the code for both the Layout Stack I want to use and the view I am using it in, however I am getting an "Extra trailing closure passed in call" error in the view I am using the Stack in.
Here is the code:
import SwiftUI
struct StairsView: View {
var body: some View {
Group{
MyStairsStack{
Text("Hello, World!")
Text("Hello, World!")
Text("Hello, World!")
}
}
}
}
struct MyStairsStack: Layout{
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize {
return .init(width: proposal.width ?? 0, height: proposal.height ?? 0)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) {
guard !subviews.isEmpty else { return }
let viewSize = maxSize(subViews: subviews)
var origin = bounds.origin
let maxWidth = bounds.width
subviews.forEach { view in
if (origin.x + (viewSize.width + 10) >= maxWidth){
origin.x = bounds.origin.x
}
view.place(at: origin, proposal: proposal)
origin.x += (viewSize.width + 10)
origin.y += (viewSize.height + 10)
}
}
private func maxSize(subViews: Subviews) -> CGSize{
subViews.map { $0.sizeThatFits(.unspecified) }.reduce(.zero) { currentMax, subviewSize in
CGSize(
width: max(currentMax.width, subviewSize.width),
height: max(currentMax.height, subviewSize.height))
}
}
}
The error is at line 5
Thank You 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!