Posts

Post not yet marked as solved
0 Replies
95 Views
I'm testing code with destination sample app but I really don't know how to add button beside of title in playbackcontrols. I can add button with customoverlay and customInfoViewControllers but it is not like apple tv's seat change button . how can I add button ?
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
180 Views
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 ) }`
Posted
by kotran.
Last updated
.
Post not yet marked as solved
1 Replies
841 Views
Hello... I really literally can't find any article addressing animation In USDZ format more detail...like transitioning multiple animation...blending each animation... even there's api for blend and transition. how can I find any source for detailing animation ? maybe it's better to use unity... I made most of app but can't find a way to animate multiple animation.
Posted
by kotran.
Last updated
.
Post not yet marked as solved
1 Replies
800 Views
it really weird. I can't add device because it is grayed out and can't add more uuid. I checked Continue button but it says as first pic, I can add more 45 iPhone but + button is still grayed out
Posted
by kotran.
Last updated
.
Post not yet marked as solved
1 Replies
944 Views
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?
Posted
by kotran.
Last updated
.
Post not yet marked as solved
1 Replies
1.3k Views
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") } } } } }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
898 Views
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)         }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
702 Views
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()     }   }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
695 Views
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)              }      }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
1 Replies
1.3k Views
I want to move toy_drummer entity with rotating toward other model entity. as you can see video, firstly, it move very well to left one then, I touch downward box entity but it move weird. video is youtu.be/3rb9W334Uwg modelentity2 is the entity that I want to move modelentityleft & modelentityright are the entity that modelentity2 should go to , so I can call objective entity *code when I touch left box entity to move, if(entity?.parent?.name=="left"){ self.parent.value4="leftarea" if(oktoadd){ self.counting = self.counting + 1 if(counting==1){ var position = firstResult.position let currentMatrix = self.modelentityleft!.transform.matrix let rotation = simd_float4x4(SCNMatrix4MakeRotation( -90.0 * .pi/180, 0,1,0)) let transform = simd_mul(currentMatrix, rotation) self.modelentity2!.move(to: transform, relativeTo: self.me, duration: 1, timingFunction: .linear) DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) { counting=0 } } } } when click downward box entity, if(ent ity?.parent?.name=="down"){ self.parent.value4="downarea" if(oktoadd){ self.counting = self.counting + 1 if(counting==1){ self.parent.value4="animating" var position = firstResult.position let currentMatrix = self.modelentitydown!.transform.matrix let rotation = simd_float4x4(SCNMatrix4MakeRotation( 90.0 * .pi/180, 0,1,0)) let transform = simd_mul(currentMatrix, rotation) print("added moving ...") self.modelentity2!.move(to: transform, relativeTo: self.me, duration: 1, timingFunction: .linear) DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) { counting=0 } } } } in my code, I firstly change rotation toward objective entity then move is there any way that I can do it more simply? (also wonder I hardcoded radian by 90 or -90 , any way to fix it by getting objective entity's position? )
Posted
by kotran.
Last updated
.
Post not yet marked as solved
2 Replies
1.2k Views
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 ?
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
622 Views
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)         }     } }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
894 Views
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?
Posted
by kotran.
Last updated
.