Post

Replies

Boosts

Views

Activity

RealityView in swiftUI look weird on vision pro
it is way above of control panel.... the code I show usdz modeling is as below `RealityView{ content in let entity = try! await Entity(named: "idle") entity.setScale([0.15,0.15,0.15], relativeTo: entity) // Enable interactions on the entity. entity.components.set(InputTargetComponent()) entity.components.set(CollisionComponent(shapes: [.generateBox(size: [2,2,2])] ) ) content.add(entity ) }`
0
0
389
Feb ’24
watch os 9 sleep analysis is not accurate as health app
let stagePredicate = HKCategoryValueSleepAnalysis.predicateForSamples(.equalTo,value: .asleepREM)         let queryPredicate = HKSamplePredicate.sample(type: HKCategoryType(.sleepAnalysis), predicate: stagePredicate)         let sleepQuery = HKSampleQueryDescriptor(predicates: [queryPredicate], sortDescriptors: [])         do{             let sleepSample = try await sleepQuery.result(for: store)                          print("sleep sample ")             print(sleepSample) with health app on iOS , it says I did rem sleep for 59 minutes. but all sum of sleep sample time is not 59 but 3.7hours. time is also not accurate. sleepSample log is as below what may be the problem?
1
0
1.1k
Jun ’22
background task is not working on watchos8
reference : https://wjwickham.com/posts/refreshing-data-in-the-background-on-watchOS/ on init function , which mean, for every 5 min it should come to handle function in Extension Delegate.swift but it won't come to handle any anything else that I should do ? let preferredDate = Date().addingTimeInterval(60 * 5)// 5min later preferredDate, userInfo: nil) { (error) in WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error: Error?) in guard error == nil else { print("Couldn't schedule background refresh.") return } print("Scheduled next background update task for: \(preferredDate)") } ExtensionDelegate.swift // // ExtensionDelegate.swift // Coffee Tracker WatchKit Extension // // Created by pedro jung on 2022/06/15. // Copyright © 2022 Apple. All rights reserved. // import Foundation import WatchKit class ExtensionDelegate: NSObject,ObservableObject, WKExtensionDelegate { func applicationDidFinishLaunching() { print("applicationDidFinishLaunching") // Perform any final initialization of your application. } func applicationDidBecomeActive() { print("applicationDidBecomeActive") // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillResignActive() { print("applicationWillResignActive") // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { for task in backgroundTasks { switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: BackgroundService.shared.updateContent() backgroundTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: BackgroundService.shared.handleDownload(urlSessionTask) default: task.setTaskCompletedWithSnapshot(false) } } } } I also check other way after checking reply of below link https://developer.apple.com/forums/thread/661892 but with no luck ... import SwiftUI import WatchKit @main struct CoffeeTrackerApp: App { @Environment(\.scenePhase) var scenePhase @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate @SceneBuilder var body: some Scene { WindowGroup { NavigationView { ContentView() } .onChange(of: scenePhase) { phase in switch phase { case .active: print("\(#function) REPORTS - App change of scenePhase to ACTIVE") case .inactive: print("\(#function) REPORTS - App change of scenePhase Inactive") case .background: let preferredDate = Date().addingTimeInterval(60 * 1)// One hour later // delegate.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error) in WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error: Error?) in guard error == nil else { print("Couldn't schedule background refresh.") return } print("Scheduled next background update task for: \(preferredDate)") } delegate.test() default: print("\(#function) REPORTS - App change of scenePhase Default") } } } } }
1
1
1.5k
Jun ’22
HKStatisticsCollectionQueryDescriptor document example is not executed.
let stepType = HKQuantityType(.stepCount)         let stepsThisWeek = HKSamplePredicate.quantitySample(type: stepType, predicate: thisWeek)         let yesterday = calendar.date(byAdding: .day, value: -1, to: calendar.startOfDay(for: now))         let every5 = DateComponents(minute:5)         let healthTypes = Set([             HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!         ])         let sumOfStepsQuery = HKStatisticsCollectionQueryDescriptor(             predicate: stepsThisWeek,             options: .cumulativeSum,             anchorDate: endDate,             intervalComponents: every5)         do {             let updateQueue = sumOfStepsQuery.results(for: store)             // Wait for the initial results and updates.             updateQueue = Task {                 for try await results in updateQueue {                     // Use the statistics collection here.                 }             }                      } catch {             //handle error             print(error)         }
0
0
941
Jun ’22
apple watch clockkit on background is not working even on sample code
https://developer.apple.com/documentation/clockkit/creating_and_updating_a_complication_s_timeline I just run sample app to check background delivery on health kit. I added caffein on my health app on phone. but it dosen't triggered on obeserver processUpdate function. func processUpdate(query: HKObserverQuery,             completionHandler: @escaping () -> Void,             error: Error?) {     print("processUpdate come!!!!")     logger.debug("Received an update from the background observer query.")           // Check for any errors that occur while setting up the observer query.     guard error == nil else {       logger.error("Unable to set up a background observer query: \(error!.localizedDescription)")       fatalError()     }           logger.debug("Responding to a background query.")           Task {               // Load the updated data from the HealthKit Store.       let success = await loadNewDataFromHealthKit()               // Check for any errors.       guard success == true else {         logger.error("Unable to query for new or deleted caffeine samples.")         fatalError()       }               // Call the completion handler when done.       completionHandler()     }   }
0
0
787
Jun ’22
detect when hand wash event is finished
Hello :) I'm trying to make Apple Watch app that can detect hand wash is finished. I followed workout app that apple provided, and succeed in getting hand wash count information . but how can I detect hand wash event when app is not foreground or executed. my full code is as below /* See LICENSE folder for this sample’s licensing information. Abstract: The start view. */ import SwiftUI import HealthKit var healthStore: HKHealthStore!     struct StartView: View {          @State var count: Int = 0     //     //  ContentView.swift     //  handwash     //     //  Created by pedro jung on 2022/06/09.     //                  var body: some View {                 Button(action: {                     checkHealthKit()                 }, label: {                     Text("Button\(self.count)")                 })             }             func checkHealthKit() {                 print(count)                 healthStore = HKHealthStore()                 let healthTypes = Set([                     HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!                 ])                 healthStore.requestAuthorization(toShare: nil, read: healthTypes)                     { (success, error) in                         fetchHandWashing()                     }             }                          func fetchHandWashing() {                 let now = Date()                 let calendar = Calendar.current                 let yesterday = calendar.date(byAdding: .day, value: -1, to: calendar.startOfDay(for: now))                 let predicate = HKQuery.predicateForSamples(withStart: yesterday, end: now, options: [])                 let sortDescriptor = [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)]                 let washingEvent = HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!                 let query = HKSampleQuery(sampleType: washingEvent,                                                 predicate: predicate,                                                 limit: HKObjectQueryNoLimit,                                                 sortDescriptors: sortDescriptor) {                     (query, results, error) in                     guard error == nil else { print("error"); return }                     let format = DateFormatter()                     format.dateFormat = "yyyy-MM-dd HH:mm:ss"                     format.timeZone   = TimeZone(identifier: "Asia/Tokyo")                     print("\(format.string(from: yesterday!)) - \(format.string(from: now)) r \(results)esult 🥳:")                     if let tmpResults = results as? [HKCategorySample] {                         print(tmpResults.count)                                                  self.count=tmpResults.count                         tmpResults.forEach { (sample) in                             print(sample)                         }                     }                 }                 healthStore.execute(query)                 healthStore.enableBackgroundDelivery(                       for: washingEvent,                       frequency: .immediate,                       withCompletion: { succeeded, error in                         guard error != nil && succeeded else {                             self.count = self.count+1                             //send information!                                                                              return                         }                       // Background delivery is enabled                     }                 )                 let query2 = HKObserverQuery(                   sampleType: washingEvent,                   predicate: nil,                   updateHandler: { query, completionHandler, error in                     defer {                       completionHandler()                     }                     guard error != nil else {                       return                     }                     // TODO                                      })                 healthStore.execute(query2)              }      }
0
0
771
Jun ’22
RealityKit - How can I calculate distance between two anchorEntity?
there's position which is simd3 and there 's anchorEntity. I want to get distance between two. how I did is var distance = distance(position, ( self.modelentity.position(relativeTo:nil) ) var distance = distance(position, ( self.modelentity.position ) but both failed because it seems calculating distance between world origin anchor not distance between position to self.modelentity. how can I calculate distance ?
2
1
1.6k
Feb ’22
anyone succeeding in playing animation sequence in WWDC example?
https://developer.apple.com/videos/play/wwdc2021/10074/ with example that apple provide, there's dive app. in app sampel code, there's animation sequence which is done by octopus entity. I think this is the only way that I can do multiple animation with swift / USDZ form. the problem is that I can't reproduce animation sequence, so, I tweaked a little bit of sample code. firstly, when scene is up, on UnderwaterView.swift, load models function, uncomment if state so that setupOctopus is triggered. so, when ar app is on, octopus is appear on scene. I changed a little bit of hidingLocation so that after 3seconds of appear octopus, it move with animation. but the problem is octopus is moving but it shows no animation... what may be the problem? struct OctopusSystem: RealityKit.System {     init(scene: RealityKit.Scene) {}     func update(context: SceneUpdateContext) {         let scene = context.scene         for octopus in scene.performQuery(OctopusComponent.query) {             print("oc 1111")             guard octopus.isEnabled else { continue }             print("oc 2222")             guard var component = octopus.components[OctopusComponent.self] as? OctopusComponent else { continue }              //            guard component.settings?.octopus.fearsCamera ?? false else { return }             print("oc 3333\(component.state)")             switch component.state {             case .hiding:                 print("oc 44444")                 guard let camera = scene.performQuery(CameraComponent.query).first(where: { _ in true }) else { continue }                                      print("oc 555")                 let fearDistance: Float = 1.0                 let distanceToCamera = octopus.distance(from: camera)                                      print("oc 5555")                 guard distanceToCamera < fearDistance else { continue }                                      print("oc 6666")                  var hidingLocation = octopus                                          hidingLocation.transform.translation.x=hidingLocation.transform.translation.x-0.01                                      print("oc 7777") //                let distance = octopus.distance(from: hidingLocation) //                guard distance > fearDistance else { continue }                  //                    print("oc 88")                 var duration = 30.5                 print("oc du...")                 // Animations                                  DispatchQueue.main.asyncAfter(deadline: .now() + 3){                     do {                         let fixedTime                             = component.animations.crawl2Swim.definition.duration                             + component.animations.swim2crawl.definition.duration                         duration = max(fixedTime, duration)                         let swimDuration = duration - fixedTime                         let swimCycleDuration = component.animations.swim.definition.duration                         let swimCycles = Int(swimDuration / swimCycleDuration)                         duration = fixedTime + Double(swimCycles) * swimCycleDuration                         if let animation = try? AnimationResource.sequence(with: [                             component.animations.crawl2Swim,                             component.animations.swim.repeat(count: swimCycles),                             component.animations.swim2crawl                         ]) {                             print("oc playanimation")                             octopus.playAnimation(animation)                         }                     }                     octopus.move(to: hidingLocation.transform, relativeTo: nil, duration: duration)                 } //                component.state = .swimming(duration)             case .swimming(var time):                 time -= context.deltaTime                 component.state = time < 0 ? .hiding : .swimming(time)             }             octopus.components.set(component)         }     } }
0
0
704
Feb ’22
How to split USDZ file by animation?
Hello ! The only way that I can use multiple animation is to have multiple USDZ with single animation according to WWDC example https://developer.apple.com/videos/play/wwdc2021/10074/ todo so, I should have file with single animation but many sources like Sketchfab.. etc it has single GLTF , USDZ file with multiple animations, I have blender but it's too difficult to export each animation to each modeling file. can anyone let me know how to split file by animation?
0
0
1k
Feb ’22
RealityKit - Measuring entity weird - measured from world origin not by entity
I tap screen and get result hit point. from that point, I want to measure distance to a 3d object placed on ar view. code is *for placing 3dobject let anchorEntity = AnchorEntity(anchor: anchor) anchorEntity.addChild(modelEntityClone) arView.scene.addAnchor(anchorEntity) *for point to measure distance to 3dobject guard let rayResult = self.view!.ray(through: normalizedIndexPoint)else {return} let results = self.view!.scene.raycast(origin: rayResult.origin, direction: rayResult.direction) if let firstResult = results.first { var position = firstResult.position var distanceing = distance(firstResult.position, self.me!.position) } I pointed very close to 3d object but it's a bit far saying 30 cm... or so, I found out that once I close to world origin, than it become almost 0... how can I measure from 3d object not from world origin?
0
0
814
Feb ’22