WatchKit

RSS for tag

Build apps that leverage watchOS features like background tasks, extended runtime sessions, and access to the Digital Crown using WatchKit.

WatchKit Documentation

Posts under WatchKit tag

136 Posts
Sort by:
Post not yet marked as solved
2 Replies
1.8k Views
I developed an iPhone/Watch app with the single target setting (new method) for Watch app projects, which will be available from Xcode14. This app uses HealthKit to retrieve information such as step count and heart rate from healthcare. The watch app is not independent and requires the iPhone app (companion app). Regarding the permission to access health care, i found some differences from the Old WatchApp Project (application project structure using WatchExtension when Xcode 13.4 or lower is used). This does not occur in the iPhone simulator or watch simulator, but only on the actual device. Both the iPhone app and watch app now display a dialog to allow access to health care In the Old WatchApp Project, if access was granted in either app, the granted access is synchronized. When checking the Health Care access status in the iPhone Settings App, permission settings for both the iPhone app and watch app are displayed independently. Because each permission setting is independent, you can choose to allow access to the iPhone app but not to allow it to the watch app. the Old WatchApp Project, permission settings for the iPhone app and watch app were synchronized, so it was not possible to have different settings for each. These behaviors are not described in the documentation. It would be understandable if the transition from watch "extension" to watch "app" is to split the app into two separate units. However, since there is no official documentation explaining this, i cannot determine whether this is the correct specification or not. Furthermore, since the companion app is required rather than a separate Watch app, having the Health Care permission settings out of sync with the companion app could cause unexpected problems and worsen the user experience. (It would be difficult and cumbersome for the user to know what settings they have made). Is there a solution to synchronize this behavior with the companion app like as the Old WatchApp Project? Do i have to go back to the project configuration (use of watchExtension) before Xcode13? I have prepared a sample project below that can test the above. https://github.com/HayakawaAKIRA/SingleTargetWatchOSApp-HealthKit reference: https://developer.apple.com/videos/play/wwdc2022/10133/ https://developer.apple.com/documentation/watchkit/wkapplication https://developer.apple.com/documentation/healthkit/setting_up_healthkit
Posted Last updated
.
Post not yet marked as solved
1 Replies
605 Views
Apple Watch Ultra 2, watchOS 10.2 I'm trying to recognize a finger double-tap gesture in watchOS 10.2 on an Apple Watch Ultra 2 or Apple Watch 9. Apple indicates watchOS will invoke primary watch button of app, but I don't know how to specify button as primary. I've written two small watchOS 10.2 SwiftUI apps to demonstrate the problem. Does anyone see what I'm missing, or can point me to relevant docs? APP #1 - simple one-button tap app. Touching button works, but double tap finger gesture seems recognized by watchOS as blue finger icon appears on top of watch display, shaking back and forth indicating it doesn't know what to do, but doesn't invoke Say Hello button. import SwiftUI struct ContentView: View { // Controls whether You did it message is shown @State private var showingSuccessMessage = false var body: some View { VStack { Button("Say Hello") { // This closure is the primary action for the button showingSuccessMessage = true // After 3 seconds, hide the success message DispatchQueue.main.asyncAfter(deadline: .now() + 3) { showingSuccessMessage = false } } // Toggle the visibility of the success message if showingSuccessMessage { Text("You Did It") } } .padding() } } #Preview { ContentView() } APP #2 - basically same app with tap gesture recognizer. Single touch of text works, but double tap gesture while seemingly recognized by watchOS as blue finger icon appears on top of watch display, shaking back and forth indicating it doesn't know what to do, also won't invoke a touch of the Say Hello text. import SwiftUI struct ContentView: View { @State private var showingSuccessMessage = false var body: some View { VStack { // The view that responds to the tap gesture Text("Tap to Say Hello") .padding() .background(Capsule().fill(Color.orange)) .foregroundColor(.white) .onTapGesture { // The action to perform on tap showingSuccessMessage = true // After 3 seconds, hide the success message DispatchQueue.main.asyncAfter(deadline: .now() + 3) { showingSuccessMessage = false } } // Toggle the visibility of the success message if showingSuccessMessage { Text("You did it") } } } } #Preview { ContentView() }
Posted Last updated
.
Post not yet marked as solved
0 Replies
518 Views
For some unknown reason, my apple watch is unable to sync with Xcode and I am unable to build to my Watch. In the Devices and Simulators window, it always shows my Apple Watch as "Connecting" and switches between the following messages: "Waiting to reconnect to [NAME]’s Apple Watch/Xcode will continue when the operation completes." or "Previous preparation error: Unsupported wire protocol version: This host does not support the wire protocol version implemented by the device." The only change that has happened between the apple watch connecting and the error occuring now is I updated my iPhone to IOS v.17. I have tried to restart all devices, Xcode, Reinstall Xcode and nothing has worked. One thing to note is I am not apart of the Apple Developer Program so I will not have access to any of the diagnostic tools apart of that membership to diagnose this issue.
Posted Last updated
.
Post not yet marked as solved
2 Replies
575 Views
I'm working on migrating my app from using CoreData to SwiftData. The swift data code generated by Xcode works correctly for the iOS and Mac Catalyst targets but it is causing a crash for the WatchOS target. It gives me this message **Fatal error: Application must register a ValueTransformer for NSSecureUnarchiveFromDataTransformer ** This attribute is the only one with a .transformable option. @Attribute(.transformable(by: "NSSecureUnarchiveFromDataTransformer")) public var linkedEntities: [UUID] = [] Changing the string NSSecureUnarchiveFromDataTransformer to NSValueTransformerName.secureUnarchiveFromDataTransformerName.rawValue causes a generic crash with no error message. The app has CloudKit integration as well (not sure if relevant). Does anyone have a similar issue and can help me on what to do here?
Posted Last updated
.
Post not yet marked as solved
0 Replies
459 Views
Project Info:A music player iOS App with watchOS app embedded. Project Structure: app target: music intent extenstion: intent (for iOS platform) watchOS app target: watchKit watchOS extension: watchKit Extension iOS app use intent extension to support SiriKit with play media intent, it works very well. now i want to support Siri on watchOS app, but i don't know how. i have tried to add new watch extension target, but it doesn't work. i t keeps saying "my app doesn't support *** instruction". Please share if I have missed to read through some documentation / reference that solves this problem.
Posted
by Highmore.
Last updated
.
Post not yet marked as solved
1 Replies
560 Views
Hello! In my project here we have 3 build modes / schemas for our iPhone app: Dev, Stage, Prod. And each one has one bundle identifier, for example, com.myproject.app-Dev, com.myproject.app-Stage and com.myproject.app. How do I can get each bundle identifier and store it inside the WKCompanionAppBundleIdentifier key automatically? Is it possible? Because, sometimes we need to build manually the Stage version here and XCode says the info.plist key for WatchOS App is different from the iPhone App.
Posted Last updated
.
Post not yet marked as solved
4 Replies
2.6k Views
Sorry for the length of this post, and all the questions. I have an iOS app written in Objective-C (too big to convert to Swift right now), and I successfully added a WatchKit app and WatchKit Extension some years ago. I also added Home Screen widgets when iOS 14 was released. With the iOS 16 betas I'd like to support Lock Screen widgets, and have also decided to move the WatchKit app/extension to SwiftUI. User journey: MyApp is launched and an item with an image is created. This item is stored in Core Data and its image is stored in a directory in the app's documents directory. A version of it is stored in NSUserDefaults in a shared app group. The user adds a Home Screen widget to show that item. Its data is pulled from the defaults, and the image is loaded from the document's directory. The user installs the Watch app and launches it. The Watch app looks inside the user defaults to retrieve the item. The iOS app sends the image to the Watch and the Watch app stores it locally (it's a small image, taking up barely a few Kb). This all works fine right now. Currently I have these targets: MyApp = main iOS app. MyApp WatchKit = Watch app storyboards and asset catalogs. MyApp WatchKit Extension = code to update the Watch interface. MyApp Widget = Home Screen widgets. MyApp IntentHandler = dynamic intents handler for the Home Screen widgets. Q1. Where do I put the code for the Lock Screen widgets? I figure these go into the My App Widget target because they're widgets and appear on the iPhone? In this video (https://developer.apple.com/videos/play/wwdc2022/10050) at 07:00 it tells you to duplicate the existing Widget target, change the bundle, change it to run on watchOS and embed it in your existing Watch App. As my original Watch App is written in Objective-C (MyApp WatchKit Extension, above) I can't/shouldn't do that, so... Q2. I think I have to create a new MyApp Watch App target, and perform the video steps on that target? I can create the views for that app, no problem. Most people update to the latest watchOS, and it's only now that watchOS 9 won't support Watch Series 3. Q3. Do I need to keep MyApp WatchKit and MyApp WatchKit Extension around? I can support older versions of watchOS if it helps my users, but they'll probably want to use the new version of watchOS, right? Can you install both versions of the app on your Watch (with watchOS 9), or does the new Swift app override the old WatchKit extension? Q4. Once I've designed the new Watch App's views in SwiftUI to replace the old WatchKit extension, where do I put the code for the complications that are being replaced? The WWDC 2022 videos (above, and a couple linked to on that page) have confused me a bit. Do I put complications views in the new MyApp Watch App target along with the other views that replace the old Watch app, or in MyApp Widget? Q5. The MyApp Widget target contains a bunch of code (WidgetUtils.swift) that populates the Home Screen widgets (and the new Lock Screen widgets), and it would fit right into the new MyApp Watch App target. Can I share that code between the two app targets just by adding WidgetUtils.swift to both target's membership? MyApp sends small images to the current MyApp WatchKit Extension. There's no code in the existing WidgetUtils.swift to handle file transfers because the images for the Home Screen widgets are pulled from the iOS app, so I need to write that in Swift for the new MyApp Watch App. The logic is already there in the old target, but I can't see any sort of equivalent to the WatchKit extension delegate where I currently handle the file transfers. Q6. Where does that go in MyApp Watch App? The existing MyApp WatchKit Extension occasionally asks MyApp for some new data. This is all done in the extension delegate which wakes up the iOS app and updates the NSUserDefaults which the extension then reads from. Q7. How do you do that in MyApp Watch App? Don't be afraid to be verbose in your responses. The more detail the better! Thank you in advance.
Posted
by darkpaw.
Last updated
.
Post not yet marked as solved
0 Replies
727 Views
I have a watch app that I have been distributed for years. But on recent Xcode 15.0.1, I started having problem: Using a eligible provision profile, I started distribute app via TestFlight and App Store, and i got: Automatic signing cannot register bundle identifier "com.virtualgs.invaders.watchkitapp.watchkitextension". Automatic signing cannot register bundle identifiers with Apple. Register your bundle identifier on https://developer.apple.com/account and then try again. No profiles for 'com.virtualgs.invaders.watchkitapp.watchkitextension' were found Xcode couldn't find any iOS App Store provisioning profiles matching 'com.virtualgs.invaders.watchkitapp.watchkitextension'. But it has gone up for many years! Any ideas?
Posted
by limtc.
Last updated
.
Post not yet marked as solved
7 Replies
2.6k Views
In WatchOS 6 a presented .sheet could be dismissed by swiping down or tapping on the navigationBarTitle. In the WatchOS 7 beta, presented sheets are no longer dismissible by either method...forcing the addition of a button to dismiss. It appears as if .sheet is now acting as .fullScreenCover within WatchOS 7. Anyone else running into this? Wondering if this is now expected behavior on WatchOS or if it's a bug...
Posted
by Eboles.
Last updated
.
Post not yet marked as solved
19 Replies
21k Views
I'm using Xcode 12 beta 3. When running my Apple Watch's target on WatchOS 7, I get this error: Warning: Error creating LLDB target at path '/Users/evan/Library/Developer/Xcode/DerivedData/audigo-cneguthkmmoulfgcprsazbryrlrl/Build/Products/Debug-watchsimulator/AudigoWatchApplication.app'- using an empty LLDB target which can cause slow memory reads from remote devices. I know this error use to be when running 32 bit frameworks on 64 bit devices, but I'm not doing that. Is this a bug? Or is there a setting I don't know of that needs to be updated?
Posted
by iEvanC.
Last updated
.
Post not yet marked as solved
0 Replies
385 Views
Hello! I'm currently working on a panic alarm app and am in the process of developing an extension for the Apple Watch. I'm trying to retrieve the location on watchOS, but I've encountered some issues. Could you provide an example or guide on how to successfully obtain the location? I suspect there might be a problem with the didFailWithError method not being recognized. Any assistance would be greatly appreciated. // Home2.swift // (watchOS) Watch App // // Created by Admin on 15.08.2023. // import SwiftUI import CoreLocation import CoreLocationUI class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { let manager = CLLocationManager() @Published var location: CLLocationCoordinate2D? override init() { super.init() manager.delegate = self } func requestLocation() { manager.requestLocation() } func checkPermission() { print("authorization status:") switch manager.authorizationStatus { case .authorizedAlways: print("always") break case .authorizedWhenInUse: print("authorized when in use") break case .notDetermined: print("notdetermined") break case .denied: print("denied") break case .restricted: print("restricted") break default: print("none of the above") break } } func requestPermission() { checkPermission() manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.first?.coordinate } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { // Error handling print("Error requesting location") } } struct Home2: View { @Binding var alarmStatus: String @StateObject var locationManager = LocationManager() @State var error: String = "" func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { // handle the error print("error ting location fra struct:" + error.message!) } func callForHelpSync() { let name = "EnBruger" /*do { try locationManager.requestPermission() print("her") let locVal = try locationManager.requestLocation() print("locVal: \(locVal)") } catch { print("locVal error: \(error)") } */ let userId = ReadlocalStorage(key: "userId") let lat: Double = 123 // TODO let long: Double = 1234 // TODO Task { let res = try await callForHelp(name: name, id: userId, lat: lat, long: long) print("callforhelp res: " + res as Any) if (res == "Sent") { //opdater binded value. alarmStatus = "Sent" } else { // vis error besked. error = "Error: \(res)" } } } var body: some View { VStack(){ Image("logo") .resizable() .aspectRatio(contentMode: .fit) Spacer() Button(action: { print("record clicked") WKInterfaceDevice.current().play(.click) }) { VStack() { Text("Aktiver Alarm") .multilineTextAlignment(.center) .padding(1.0) .font(.system(size: 22, weight: .bold)) Text("(Hold inde)") .multilineTextAlignment(.center) .padding(1.0) } } .padding(11.0) .background(/*@START_MENU_TOKEN@*//*@PLACEHOLDER=View@*/Color(hue: 1.0, saturation: 0.966, brightness: 0.824)/*@END_MENU_TOKEN@*/) .buttonStyle(.plain) .simultaneousGesture(LongPressGesture(minimumDuration: 2).onEnded({_ in callForHelpSync()})) Text(self.error).font(.footnote).foregroundColor(Color.red).fixedSize(horizontal: false, vertical: true) Spacer() Button(action: { print("test button 1 clicked") locationManager.requestPermission() }) { VStack() { Text("Test Knap 1") .multilineTextAlignment(.center) .padding(1.0) .font(.system(size: 22, weight: .bold)) } } .padding(6.0) .background(.blue) .buttonStyle(.plain) if let location = locationManager.location { Text("Your location: \(location.latitude), \(location.longitude)") } LocationButton { locationManager.requestLocation() } .frame(height: 44) .padding() Button(action: { print("test button 2 clicked") var lh = LocationHandler() lh.requestLocation() }) { VStack() { Text("Test Knap 2") .multilineTextAlignment(.center) .padding(1.0) .font(.system(size: 22, weight: .bold)) } } .padding(6.0) .background(.blue) .buttonStyle(.plain) } .background(/*@START_MENU_TOKEN@*//*@PLACEHOLDER=View@*/Color.white/*@END_MENU_TOKEN@*/) } } struct Home2_Previews: PreviewProvider { static var previews: some View { @State var alarmStatus = "none" Home2(alarmStatus: $alarmStatus) } }
Posted Last updated
.
Post not yet marked as solved
1 Replies
379 Views
Hi everyone, I am new to app development, and I am learning and develop a simple app with iPhone and Apple Watch. Initially, i was successful in building and installing the app. However, all of a sudden, the error /Unable to install "SwingMonitor"/ started to appear and I really struggle to find a solution. I even tried to start from scratch, but the issue remains. Please could you help me? I will be able to provide info.plist content and build phase/setting information as required. Many thanks in advance.
Posted Last updated
.
Post not yet marked as solved
0 Replies
377 Views
I have a WKInterfaceLabel that spans two other objects (could be most anything, but generally solid color). (I'm using Interface Builder). One object is light and the other is dark. I'd like the part of the label on the light object to be black, and the part on the dark object to be white. See the example below. Is there any way to "mask" out part of the label so that the objects behind show through? I could have two labels, one black and one white, but would need to mask out each half. I can't simply half cover each label to mask it out because that will mask out the other.
Posted
by MowinMan.
Last updated
.
Post not yet marked as solved
2 Replies
1.4k Views
Hey, so I am creating an app that will get the core motion data (accelerometer and gyroscope) from my apple watch and stream it onto a console. I am able to get accelerometer data but not a gyroscope from my apple watch. When I try it with my phone I get both. So is gyroscope data not available for the apple watch?
Posted
by RuttabH.
Last updated
.
Post not yet marked as solved
0 Replies
343 Views
I have a WatchOS app with scrollable views. Depending on the state of the app I would like to receive crown rotation events. To achieve this behavior I have set up a timer that calls the focus() method of the crownSequencer. In the Apple Watch simulator in XCode the app behaves consistently and there are no problems. However, some users (not all) report that rotating the crown does not work. What could be the reason for this behavior? Here is the relevant code: import WatchKit import Foundation import HealthKit class MyInterfaceController: WKInterfaceController { var controlTimer: Timer?; var restTimer: Timer?; var timer: Timer?; override func awake(withContext context: Any?) { super.awake(withContext: context) setupTimers() } override func willActivate() { super.willActivate() setupTimers() } override func didAppear() { super.didAppear() setupTimers() } func setupTimers() { clearTimers() restTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { _ in // Do something }); timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { _ in // Do something }); controlTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: { _ in if (someCondition == false) { self.crownSequencer.resignFocus() } else { self.crownSequencer.delegate = self self.crownSequencer.focus() } }); } func clearTimers() { controlTimer?.invalidate() controlTimer = nil restTimer?.invalidate() restTimer = nil timer?.invalidate() timer = nil } } extension MyInterfaceController : WKCrownDelegate { func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) { if (rotationalDelta > 0.2) { // Do something } else if (rotationalDelta < -0.2) { // Do something } } }
Posted
by gizmodus.
Last updated
.
Post not yet marked as solved
2 Replies
1.2k Views
Hello, I try to add a couple of Complications to my App. Most of the Complications needs to be Configurable, so I use an IntentConfiguration for them. I use this recommendations function to create my complications.     func recommendations() -> [IntentRecommendation<ConfigurationIntent>] {         var recommendations = [IntentRecommendation<ConfigurationIntent>]()        for vehicle in vehicleStatusList {             let intent = ConfigurationIntent() intent.vehicleItem = VehicleItem(identifier: vehicle.id, display: vehicle.name)             recommendations.append(IntentRecommendation(intent:  intent, description: vehicle.name))         }         return recommendations     } But with this I get the result from the screenshot... How can I change this to get a better User Experience? When I click one item in the List, I get a correct Complication. But it would be nice to have a change to name them correctly... The first in the List is a StaticConfiguration...
Posted
by Urkman.
Last updated
.
Post not yet marked as solved
4 Replies
960 Views
For some reason I am not receiving HKQuantityTypeIdentifierDistanceSwimming samples when using the watchOS 10 beta (8). The same code works fine on watchOS 9 but not on watchOS 10. I have tried specifically enabling them in the collection types for the live builder and /or starting a query for them, but neither approach is causing any samples to be returned to the app. Is this a known issue? Has something changed for swimming in watchOS 10? Thanks in advance.
Posted
by cfc.
Last updated
.