Post

Replies

Boosts

Views

Activity

Get fetch request from a different class/function
How can I get the fetch request from a different class so I can re-use it on different views and functions on other files? If you see on the code below, I have to call the fetch request twice in different classes, I want to create a class with a function called: readData so when I call it: readData() it will return the @FetchRequest . I'm using SwiftUI. This is the code I was mentioning:import SwiftUI struct ContentView: View { @ObservedObject var myClass = MyClass() @FetchRequest( entity: ProgrammingLanguage.entity(), sortDescriptors: [ NSSortDescriptor(keyPath: \ProgrammingLanguage.id, ascending: true) ] ) var languages: FetchedResults @Environment(\.managedObjectContext) var managedObjectContext var body: some View { NavigationView { VStack { List(languages, id: \.self) { language in Text(self.language.name ?? "") } } } .onAppear{ // Data not refreshed self.myClass.createData() } } } class MyClass: ObservableObject { @FetchRequest( entity: ProgrammingLanguage.entity(), sortDescriptors: [ NSSortDescriptor(keyPath: \ProgrammingLanguage.id, ascending: true) ] ) var languages: FetchedResults @Environment(\.managedObjectContext) var managedObjectContext func createData() { for i in 1...5 { let language = ProgrammingLanguage(context: self.managedObjectContext) language.id = Int32(i) // << here !! language.name = "\(i) SwiftUI" do { try self.managedObjectContext.save() } catch { } } } func readData() { // How can I return the objects here? Not in a loop, but as a fetch request so I can use that fetch request on other views } }
3
0
2.6k
May ’20
Type '()' cannot conform to 'View error
I'm trying to create a function called ResetDay so I can call it on some other view, but I keep getting the error:Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocolsclass MyClass { // ************************* CORE DATA ************************* @FetchRequest( entity: Meals.entity(), sortDescriptors: [] ) var mealData: FetchedResults @Environment(\.managedObjectContext) var managedObjectContext // **************************************************************** func ResetDay() { ForEach(mealData, id: \.self) { meal in print(meal.status!) } } }What's going on?
11
1
26k
May ’20
View not refreshed when .onAppear runs SwiftUI
I made a little example replicating what's going on, if you run it, and click on set future date, and wit 5 seconds, you'll see that the box hasn't changed color, after that, click on Go to view 2 and go back to view 1 and you'll see how the box color changes... that's what's happening in my code too:import SwiftUI struct ContentView: View { @State var past = Date() @State var futuredate = Date() var body: some View { NavigationView { VStack { NavigationLink(destination: DetailView()) { Text("Go to view 2") } Button("set future date") { self.futuredate = self.past.addingTimeInterval(5) } VStack { if (past < futuredate) { Button(action: { }) { Text("") } .padding() .background(Color.blue) } else { Button(action: { }) { Text("") } .padding() .background(Color.black) } } .onAppear { self.past = Date() } } } } } struct DetailView: View { @Environment(\.presentationMode) var presentationMode: Binding var body: some View { Text("View 2") } }Any help would be appreciated
14
0
6.0k
May ’20
Initialize Core Data Objects SwiftUI
I'm trying to initiate the data so when the user installs the app for the first time it has some data. The init is not working, but why?For CRUD operations on Core Data I'm using an `xcdatamodeld` file with an entity called `ProgrammingLanguage` that has two string attributes: “name” and “creator”. Here is the code:struct ContentView: View { @Environment(\.managedObjectContext) var managedObjectContext @FetchRequest( entity: ProgrammingLanguage.entity(), sortDescriptors: [ NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true), ] ) var languages: FetchedResults init() { let language = ProgrammingLanguage(context: self.managedObjectContext) language.name = "SwiftUI" language.creator = "Some text" do { try self.managedObjectContext.save() } catch { } } var body: some View { NavigationView { List { ForEach(languages, id: \.self) { language in Button(action: { }) { Text("Creator: \(language.creator ?? "Anonymous")") } } } } } }It's as if it is not saving it. What's going on here? That init should create the data on the db and I would be able to read it on the view...
4
0
5.7k
May ’20
Update Cora Data Object
I'm creating a new xcdatamodeld file and create an entity called ProgrammingLanguage that has two string attributes: “name” and “creator”.then, using it here to create new objects:import SwiftUI struct ContentView: View { // Anywhere you need to create Core Data objects you should add an @Environment property to ContentView to read the managed object context right out: @Environment(\.managedObjectContext) var managedObjectContext var body: some View { Button(action: { let language = ProgrammingLanguage(context: self.managedObjectContext) language.name = "Python" language.creator = "Guido van Rossum" // See whether your managed object context has any changes if self.managedObjectContext.hasChanges { // Save the context whenever is appropriate do { try self.managedObjectContext.save() } catch { // handle the Core Data error } } }) { Text("Insert example language") } } }How can I modify that object once created?Thank you
0
0
273
May ’20
Picker with hours and minutes
Hi, I'm trying to accomplish this picker:Right now I have this:HStack { Spacer() Picker("", selection: $hours){ ForEach(0..<4, id: \.self) { i in Text("\(i) hours").tag(i) } } .pickerStyle(WheelPickerStyle()) .frame(width: 180) .clipped() Picker("", selection: $minutes){ ForEach(0..<60, id: \.self) { i in Text("\(i) min").tag(i) } } .pickerStyle(WheelPickerStyle()) .frame(width: 180) .clipped() Spacer() }and even though that works, the design is very bad: the pickers are separated in the UI, is there a better way to do it than my implementation?The most important one, it's visible all the time, I want something like the first image that you click, and it expands, or a popup is presented (not sure which UI is more apple style)How can I fix the above?Thank you
3
0
6.6k
Apr ’20
Track if notification was fired
Hi, I have this:import SwiftUI import UserNotifications struct ContentView: View { var body: some View { VStack { Button("Request Permission") { RequestNotificationsAccess() } Button("Schedule Notification") { ScheduleNotification() } } } } func RequestNotificationsAccess() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("All set!") } else if let error = error { print(error.localizedDescription) } } } func ScheduleNotification() { let content = UNMutableNotificationContent() content.title = "Title:" content.subtitle = "some text" content.sound = UNNotificationSound.default // show this notification five seconds from now let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) // choose a random identifier let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) // add our notification request UNUserNotificationCenter.current().add(request) }It works great but when I click multiple times on the button, the notification appears multiple times, how can I track if it was fired already and if so, don't display anything?Thanks
1
0
496
Apr ’20
Maintain state of the app while closed
Hi, I'm working on an app to practice which has a counter with the following:func start() { timerMode = .running playSound(sound: "piano-1", type: "mp3") timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in if self.secondsLeft == 0 { self.reset() self.next() self.start() } self.secondsLeft -= 1 }) }The problem is that when it reaches 0, it it suppoused to restart the counter, but it doesn't WHEN it's closed or with the screen off, and if I quit the app it resets. How can I keep the state of the app when it's closed or screen off?Thanks
1
0
428
Apr ’20