Hello
Does anyone know how to use real time image recognition in SwiftUI with a Create ML model.
Thank you
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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
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 developing an app with SwiftUI using CoreData and iCloudKit to sync data between platforms.
The problem is that the iCloud background update is not being triggered when staying in the application. If I make changes on both systems, the changes are being pushed, however not visible on the other device.
I need to reload the app, close the app and open again.
I already enabled iCloud capability, background notifications and push notifications.
This is my persistentContainer
var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Test7")
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
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges{
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
This is my model
class ItemsModel: ObservableObject {
init() {
readData()
}
@Published var dataInputs: [Item] = []
let context = persistentContainer.viewContext
func readData(){
let request: NSFetchRequest<Item> = Item.fetchRequest()
do {
let results = try context.fetch(request)
self.dataInputs = results
} catch {
print(error.localizedDescription)
}
}
func addItem(todo: String, date: Date){
let entity = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item
entity.todo = todo
entity.date = date
do {
try context.save()
self.dataInputs.append(entity)
} catch {
print(error.localizedDescription)
}
}
func deleteItems(indexSet: IndexSet){
for index in indexSet{
do {
let obj = dataInputs[index]
context.delete(obj)
try context.save()
let index = dataInputs.firstIndex(of: obj)
dataInputs.remove(at: index!)
} catch {
print(error.localizedDescription)
}
}
}
}
and this is my view
struct ContentView: View {
@EnvironmentObject var items: ItemsModel
var body: some View {
NavigationView{
List {
ForEach(items.dataInputs) { item in
Text("Item at \(item.date!)")
}
.onDelete(perform: items.deleteItems)
}
.toolbar {
Button {
items.addItem(todo: "Hello", date: Date())
} label: {
Image(systemName: "plus")
}
}
}
}
}
Thank you
Hello
Is there a way to share data stored in CloudKit and CoreData between iOS and watchOS in SwiftUI? I am using the same CoreData file both, and I am using the same PersistenceController file both, and I am using the same CloudKit container for both.
I tried adding the App Groups capability to all the targets, but it is not working.
(I already enabled iCloud capability, Push notification capability and background Modes capability for both iOS and WatchOS)
PersistenceController:
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "Test7")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
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:
struct ContentView: View {
@FetchRequest(
entity: Item.entity(),
sortDescriptors: []
) var items: FetchedResults<Item>
@Environment(\.managedObjectContext) private var context
var body: some View {
NavigationView{
List {
ForEach(items) { item in
Text("Item at \(item.date!)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
Button {
addItem()
} label: {
Image(systemName: "plus")
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: context)
newItem.date = Date()
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(context.delete)
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
Thank you
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
How can I set up local notifications that repeat every X minutes from a certain hour to another hour.
For example, I want to receive a notification every 60 minutes starting from 12:00 AM to 10:00 PM?
func scheduleNotifications() {
let content = UNMutableNotificationContent()
content.title = "App"
content.subtitle = "App"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
With this code I can schedule a notification every minute, however, I cannot decide from what time it should start or when it stops.
Any ideas?
Thank you!
Hello
Everytime I run a project I get this popup: The document “iosfwd” could not be saved. You don’t have permission.
How do I fix it?
Thank you
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
In my previous post I asked:
https://developer.apple.com/forums/thread/689720
(Read my previous post before continuing, please)
My question now is, if I compare Dates between each other will they be formatted or not, and how would I fix this?
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
In my app I have a list of items in a ForEach and at the end of the ForEach there is a .onDelete. (This is in a View that I called AllHistoryView)
The items are represented by a CoreData NSManagedObject that I called LifetimeInputs with 3 properties:
date: Date, imageTemplate: String, valori: Double
The problem is that, when I add (in a different View) an item with the date of tomorrow and then I add another to item with the date of today and then go to the AllHistoryView where there are all the items and delete slowly the item with date of tomorrow (especially at the end of the swipe action) instead of deleting the item that I swiped it deletes the on before it, how can I solve this problem?
Here is the AllHistoryView code:
import SwiftUI
import CoreData
struct AllHistoryView: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest(entity: LifetimeInputs.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \LifetimeInputs.date, ascending: true)], animation: .default) var lifetimeInputsModel: FetchedResults<LifetimeInputs>
@State private var text: String = ""
@State private var ascending: Bool = true
@State var sortDescriptor: NSSortDescriptor = NSSortDescriptor(keyPath: \LifetimeInputs.date, ascending: true)
@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
}
}
}
var body: some View {
theView()
}
@ViewBuilder
func theView() -> some View{
NavigationView{
if !lifetimeInputsModel.isEmpty{
List{
SectionList(sortDescripter: sortDescriptor, text: $text)
.environment(\.managedObjectContext, viewContext)
.onChange(of: ascending, perform: { _ in
if ascending {
withAnimation {
sortDescriptor = NSSortDescriptor(keyPath: \LifetimeInputs.date, ascending: true)
}
} else {
withAnimation {
sortDescriptor = NSSortDescriptor(keyPath: \LifetimeInputs.date, ascending: false)
}
}
})
}
.searchable(text: $text, placement: .navigationBarDrawer, prompt: "Quantity or date".localized())
.navigationBarTitle("History", displayMode: .inline)
.toolbar{
ToolbarItem(placement: .automatic) {
Image(systemName: "arrow.up.arrow.down.circle")
.foregroundColor(.primary)
.font(.system(size: size))
.rotation3DEffect(.degrees(ascending ? 0 : 180), axis: (x: 1, y: 0, z: 0))
.opacity(0.5)
.onTapGesture {
ascending.toggle()
}
}
}
} else{
VStack{
Text("No Data".localized())
.font(.largeTitle)
.fontWeight(.semibold)
.foregroundColor(.secondary)
}
.padding(.bottom)
.navigationBarTitle("History", displayMode: .inline)
}
}
}
}
struct SectionList: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest var lifetimeInputsModel: FetchedResults<LifetimeInputs>
@Binding var text: String
init(sortDescripter: NSSortDescriptor, text: Binding<String>) {
let request: NSFetchRequest<LifetimeInputs> = LifetimeInputs.fetchRequest()
request.sortDescriptors = [sortDescripter]
_lifetimeInputsModel = FetchRequest<LifetimeInputs>(fetchRequest: request)
self._text = text
}
@FetchRequest(entity: Limit.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Limit.date, ascending: true)], animation: .default) 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()
var body: some View {
Section{
ForEach(lifetimeInputsModel.filter { text.isEmpty || "\($0)".contains(text) }){ lifetimeInputs in
HStack{
Text("\(lifetimeInputs.valori, specifier: format(unita: !limit.isEmpty ? limit[0].unita ?? ml : ml)) \(!limit.isEmpty ? limit[0].unita ?? ml: ml)")
.font(.system(size: size))
Spacer()
Text("\(dateFormatter.string(from: lifetimeInputs.date ?? Date()))")
.font(.system(size: size))
}
}
.onDelete(perform: { offsets in
lifeTimeInputsViewModel.deleteItems(offsets: offsets)
})
} header: {
Text("History".localized()).font(.system(size: size - 4))
}
}
}
Thank You very much!