WatchKit

RSS for tag

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

Posts under WatchKit tag

138 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

My Custom Watchface
Dear all, i am a music conductor and developer, and to fulfill my joy with music i recently developed a WatchFace and some apps for a non-apple watch called "PineTime". My whole development is done in c++ and is available at https://github.com/luto65/PineConductor/ Since I am aswell an apple developer, and most of my friends have apple watches, i am now porting those c++ apps to the apple watch. I just finished the very first one, that is actually a watch Face I now ported it to appleWatch and it looks pretty similar too (here a screenshot from the simulator) I would like to now remove the annoying digital hour on the top right corner, and then sell it as new custom face, together with my other swift-ports of my original c++ applications. Looking forward any feedback.
1
0
385
Oct ’24
Can I fix this big difference between swiftui preview and actual watch widget layout?
Hi, working on customising my live activity Smart Stack layout for ios18. A thing that is very frustrating is that I consistently looks different for me in the Xcode preview and on the actual watch. See attached screenshots below. The sizes are different, and italic doesn't work on the watch, for example. It makes it time-consuming and unpredictable, so I was wondering if this is a known issue or if I'm doing something wrong, and also can I do anything? thanks edit: this is the layout: var body: some View { VStack(alignment: .center, spacing:4) { HStack(alignment: .center) { IconView(resource: "n-compact-w", bgColor: Color.checkedIn, padding: 2, paddingRight: 6, paddingBottom: 6) .frame(maxWidth: 25, maxHeight: 25).aspectRatio(1, contentMode: .fit) Text("Checked Out") .font(.title3).bold() } Text(status.loc) .font(.headline) .multilineTextAlignment(.center) Text(FormatUtils.getFormattedDateTime(status.time)).font(.subheadline) .multilineTextAlignment(.center).italic() } }
4
0
517
Oct ’24
Optimize watchOS CMSensorDataList parsing
I am trying to parse CMSensorDataList in watchOS. The maximum batch of data is comprised of 30 minutes. The sampling rate is 50Hz, which makes it 90,000 records for 30 minutes. We iterate over each item and finally write the data to a CSV file. As this is a slow processing keeping in view the execution limits of watchOS, the process suspends when app goes to the background. This way, it takes too much time to parse a significant time data. My question is, is there a way we can serialize this CMSensorDataList as a whole and transfer it to the phone using WCSession? Or is there another effective way to achieve this?
0
0
323
Oct ’24
How can I use an image for my live activity smartstack layout?
Hello, I am updating my live activity for the new ios18 Smart Stack functionality. I got it working through the WWDC session (Bring your live activities to Apple watch). I'm doing supplementalActivityFamilies([.small]) and then a custom layout in the .small ActivityFamily However, any images I try to use in the Smart Stack just show up as grey squares. (it works on the phone live activity) I suspect it's because my app images are not moved over to the watch? Because I don't have a watch app and such no watch target? If anyone can help me understand if there's anything I can do in order to have a custom image show up on the smart stack, I'd be very grateful.
3
0
544
Oct ’24
Hand Gesture Controls in an Apple Watch App
Hello everyone! I want to add hand gesture controls to my Apple Watch app. Specifically, I’m looking to implement the following gestures: 1. Tapping index finger and thumb together once 2. Tapping index finger and thumb together twice 3. Fist clench 4. Double fist clench Each gesture should trigger a different action within the app. However, I can’t find any information on how to implement this. I only came across an example using .handGestureShortcut(.primaryAction) (Enabling the double-tap gesture on Apple Watch https://developer.apple.com/documentation/watchOS-Apps/enabling-double-tap), but I need to handle four distinct gestures. Is this possible in watchOS 11? Any guidance or examples would be greatly appreciated! Thank you!
1
0
495
Oct ’24
WatchOS local notifications delayed
I'm scheduling local notifications on my WatchOS app, but they are always alerting exactly 13 seconds later than scheduled. I have read other users having the exact same issue but there is no solution anywhere. I'm not sure how one is supposed to write any sort of timer app when they are always coming in delayed. Any idea why this occurs and how to resolve it? For now I am subtracting 13 seconds from the end time, but that's not really a solution I'm happy with. Thanks
2
0
556
Oct ’24
How to disable Live Activity on Apple Watch while keeping it enabled on iPhone?
I'm using Live Activity features in my app, but I want to customize the user experience across different Apple devices. Specifically, I'd like to: Keep Live Activity enabled and functioning on the iPhone Disable or prevent Live Activity from appearing on the connected Apple Watch Is this level of device-specific control possible with Live Activity? If so, what's the best approach to implement this functionality? What I've tried: I've looked through Apple's documentation on Live Activity, but couldn't find specific information about device-level control. I've experimented with ActivityKit, but haven't found a clear way to distinguish between iPhone and Apple Watch when pushing updates.
4
0
1k
Oct ’24
Getting kclErrorDomain error : 1
Hi, I created an iOS app compatible watchOS app which was running perfectly fine before I updated my Xcode to use iPhone16. But after updating, I started to get kclErrorDomain error: 1 and I am not sure why is it happening after update. I am trying to use coreLocation module as- import Foundation import CoreLocation import Combine class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { private var locationManager = CLLocationManager() @Published var location: CLLocation? override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { self.location = location print("Updated location: \(location.coordinate.latitude), \(location.coordinate.longitude)") } else { print("No locations received") } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } } and I am trying to use it as- @StateObject private var locationManager = LocationManager() guard let currentLocation = locationManager.location else { signInError = "Location not available" isLoading = false return } let latitude = currentLocation.coordinate.latitude let longitude = currentLocation.coordinate.longitude sendToBackend(email: email, password: password, deviceName: deviceName, deviceModel: deviceModel, deviceIdentifier: deviceIdentifier, latitude: latitude, longitude: longitude) Can someone help me regarding this?
1
0
563
Oct ’24
SwiftUI - WatchKit TextField Keyboard closed immediately before entering text
The TextField Shows and When selected opens the keyboard very slowly and before entering text closes immediately with these messages. <PUICQuickboardController: 0x6000029111f0> [0x6000029111f0-1] presentation watchdog expired! <PUICQuickboardController: 0x6000029111f0> [0x6000029111f0-1] is no longer the current presentation, we must have timed out... This App was working fine in Simulator and test devices until recently.
0
0
321
Oct ’24
Casting `[String: Any]` to `[String: any Sendable]`
I have a simple wrapper class around WCSession to allow for easier unit testing. I'm trying to update it to Swift 6 concurrency standards, but running into some issues. One of them is in the sendMessage function (docs here It takes [String: Any] as a param, and returns them as the reply. Here's my code that calls this: @discardableResult public func sendMessage(_ message: [String: Any]) async throws -&gt; [String: Any] { return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation&lt;[String: Any], Error&gt;) in wcSession.sendMessage(message) { response in continuation.resume(returning: response) // ERROR HERE } errorHandler: { error in continuation.resume(throwing: error) } } } However, I get this error: Sending 'response' risks causing data races; this is an error in the Swift 6 language mode Which I think is because Any is not Sendable. I tried casting [String: Any] to [String: any Sendable] but then it says: Conditional cast from '[String : Any]' to '[String : any Sendable]' always succeeds Any ideas on how to get this to work?
3
1
873
Oct ’24
App Not Appearing in "Available Apps" List in Watch App
I’ve developed an Apple Watch extension for an existing iOS app. When I run the app on the watch via Xcode using the simulator, everything works fine. However, when I try to install it on my iPhone, the Watch app doesn’t show it in the "Available Apps" list, so I can't install it on the watch. The Apple Watch is connected to my iPhone, and I can see other apps available for installation without any issues. I also created a brand new project with watchOS support to troubleshoot, but the same problem occurred. Any ideas on how to resolve this?
0
0
409
Oct ’24
WatchOS suspends process execution when faces down
I am writing an app that records accelerometer data in the background. When we call sensor.accelerometerData(from:to:), the for loop when iterating CMSensorDataList suspends/pauses as the watch screen turns off and resumes when app comes to foreground. Is there a way we can keep the processing on until it completes? I used Location Updates capability in Background Modes as a hack but it will make my app rejected from App store just to acquire capability for background execution. Please note that our data is comprised of larger sets, say hours. We retrieve data in batches of 30 minutes each but this also does not complete.
1
0
452
Oct ’24
Home app on apple watch
This is a repost as it seems to be a reoccurring issue. ‘I have a number of accessories setup on homekit and everything works fine from my phone. However, recently, no homekit accessories works on apple watch, everything is no response (on watch face or through siri). Everything still works on the phone. iOS 16.5, Watch OS 9.5.1’ I have the same issue with iPhone 14 pro ios 18.1 apple watch 9 watch os 11.1 tried turning off and on restarting app renaming home this is beta software but was hoping there was an easy fix.
1
0
358
Oct ’24
WKApplication.didBecomeActiveNotification not fired when Control Center (or other system overlay view) dismissed by system
https://forums.developer.apple.com/forums/thread/685317 Having read the above discussion, I can add there’s one problematic exception on watchOS to the rule that .didBecomeActiveNotification is fired when the Control Center or any other overlay (such as a long-look notification) is dismissed. It’s when it’s dismissed not by the user, but just allowed to dsimiss itself after a period (as determined by Settings > Wake Duration). This is a problem for any Watch workout app because when one of these overlays is covering the app, it’s considered by the system to be backgounded for purposes of applying the 15% avg CPU load over 60 seconds criteria for being terminated for using too much CPU in the background, so I have discovered. In the case of these overlays covering an app, the app never gets a .didEnterBackgroundNotification call to know that it should attempt to reduce its activity, when the user presses the Side Button to show the Control Center, which is by design, as I understand it. The app does get a .willResignActiveNotification when the Control Center covers it, but there is no corresponding .didBecomeActiveNotification when the system dismisses the Control Center after 2 minutes or so. So if the app reduces its actvity in an attempt to reduce CPU load when covered by the Control Center overlay, it has no way to know it has become active again, in the special case of the Control Center timing out and being dismissed by the system. What could be done to reduce the likelihood of the system terminating the app in this situation, and maintain the app's functionality and usability?
2
0
432
Oct ’24
"validate settings" missing from xcode16 ?
I’d like to migrate my watchOS app (bundled with an iOS app) from a dual-target to a single-target setup. I remember Xcode used to have a menu item (Editor -> Validate Settings) that would prompt you to initiate the migration process. However, I can’t seem to find a ‘Validate Settings’ option in the latest Xcode 16. Has "Validate Settings" been removed in xcode16 ? Thanks!
1
0
405
Sep ’24
scenePhase change on display cadence change
My Watch app is a workout app that has to be careful to minimize CPU load when backgrounded to get below the 15% avg/60 s in order to avoid being terminated by the system. Accordingly I have logic to detect a transition to the background using a .onChange(of: scenePhase) { phase in… } handler which works well for cases where the app is backgrounded - it is able to reduce its CPU load to just 6-9% while backgrounded. But a special case of the change to scenePhase presents a challenge - when an overlay such as the Control Center or a long-look notification presents, there is no transition to .background, only to .inactive. This is a problem because the system nevertheless imposes the background CPU limit on the app while it’s being covered by the overlay, even though the app didn’t get the .background transition on the scenePhase handler. To further complicate matters, it now seems with watchOS 11 that whenever a transition is made in the screen cadence from .live to .seconds, the scenePhase handler is called with a transition to .inactive. Which is a problem because this transition has to be distinguished from the case of the overlay presentation - the cadence change has no CPU usage implications as long as the app remains foregrounded, but the overlay presentation does, and the system will terminate the app if it exceeds 15% avg/60s. My question: how can I distinguish between the two causes of the transition to .inactive for the two cases: 1) when the overlay presents, and 2) when the display shifts to the slow cadence?
0
0
286
Sep ’24
watchOS SwiftUI background task not working
I'm attempting to create a standalone watchOS app that fetches the prayer timings of my local mosque in JSON format via an API call. I want the app to fetch the prayer timings in the background, but only once per day, at the start of the day (when prayer timings change, i.e., midnight). I'm trying to implement this using SwiftUI's backgroundTask modifier as explained in the docs and in this WWDC22 video. I made sure to enable the Background Modes capability, and this is what my app's Info.plist looks like: However, I've been unable to get it to work. I would appreciate any assistance I can get and feedback for improvements I can make, even with the Info.plist if anything is incorrect about it. Thank you! This is what I have so far: // PrayerTimesCompanionApp.swift // PrayerTimesCompanion Watch App import SwiftUI import WatchKit @main struct PrayerTimesCompanion_Watch_AppApp: App { var body: some Scene { WindowGroup { ContentView() } .backgroundTask(.appRefresh("TIMINGS_REFRESH")) { print("Found matching task") scheduleNextBackgroundRefresh() } } } // Schedule the next background refresh func scheduleNextBackgroundRefresh() { let today = Calendar.current.startOfDay(for: .now) if let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today) { WKApplication.shared().scheduleBackgroundRefresh(withPreferredDate: tomorrow, userInfo: "TIMINGS_REFRESH" as NSSecureCoding & NSObjectProtocol) { error in if error != nil { fatalError("*** An error occurred while scheduling the background refresh task. ***") } print("*** Scheduled! ***") } } } // ContentView.swift // PrayerTimesCompanion Watch App import SwiftUI struct ContentView: View { @StateObject var prayerTimeModel = PrayerTimesModel() var body: some View { List { VStack { VStack(spacing: 15) { // Table Header HStack { Text("Prayer") .bold() .frame(maxWidth: .infinity, alignment: .leading) // Align to the left Text("Iqamah") .bold() .frame(maxWidth: .infinity, alignment: .trailing) // Align to the right } .padding() // Table Rows (5 prayers) ForEach(prayerTimeModel.prayerTimes.data.iqamah, id: \.date) { iqamah in rowView(prayer: "Fajr", time: iqamah.fajr) rowView(prayer: "Zuhr", time: iqamah.zuhr) rowView(prayer: "Asr", time: iqamah.asr) rowView(prayer: "Maghrib", time: iqamah.maghrib) rowView(prayer: "Isha", time: iqamah.isha) } } .padding() } .padding() .onAppear { prayerTimeModel.fetch() } } .edgesIgnoringSafeArea(.top) } func rowView(prayer: String, time: String) -> some View { HStack { Text(prayer) .frame(maxWidth: .infinity, alignment: .leading) Text(time) .frame(maxWidth: .infinity, alignment: .trailing) } } } #Preview { ContentView() } // PrayerTimesModel.swift // PrayerTimesCompanion Watch App import Foundation import SwiftUI // Main struct for the response struct PrayerTimesResponse: Codable { let status: String var data: SalahData let message: [String] } // Struct for the data section struct SalahData: Codable { var salah: [Salah] var iqamah: [Iqamah] } // Struct for Salah times struct Salah: Codable { let date: String let hijriDate: String let hijriMonth: String let day: String var fajr: String let sunrise: String var zuhr: String var asr: String var maghrib: String var isha: String enum CodingKeys: String, CodingKey { case date, hijriDate = "hijri_date", hijriMonth = "hijri_month", day, fajr, sunrise, zuhr, asr, maghrib, isha } } // Struct for Iqamah times struct Iqamah: Codable { let date: String var fajr: String var zuhr: String var asr: String var maghrib: String var isha: String let jummah1: String let jummah2: String enum CodingKeys: String, CodingKey { case date, fajr, zuhr, asr, maghrib, isha, jummah1 = "jummah1", jummah2 = "jummah2" } } class PrayerTimesModel: ObservableObject { @Published var prayerTimes: PrayerTimesResponse = PrayerTimesResponse( status: "Unknown", data: SalahData( salah: [Salah(date: "", hijriDate: "", hijriMonth: "", day: "", fajr: "", sunrise: "", zuhr: "", asr: "", maghrib: "", isha: "")], iqamah: [Iqamah(date: "", fajr: "", zuhr: "", asr: "", maghrib: "", isha: "", jummah1: "", jummah2: "")]), message: ["No data available"] ) // fetches the local mosque's prayer timings via an API call func fetch() { guard let url = URL(string: "https://masjidal.com/api/v1/time/range?masjid_id=3OA87VLp") else { return } let task = URLSession.shared.dataTask(with: url) { [self] data, _, error in guard let data = data, error == nil else { return } // Convert to JSON do { var prayerTimes = try JSONDecoder().decode(PrayerTimesResponse.self, from: data) DispatchQueue.main.async { self.prayerTimes = prayerTimes } } catch { print(error) } } task.resume() } }
0
0
485
Sep ’24
What does it mean? Bug description: your app displayed an error message when we used Sign in with Apple and did not proceed.
What does it mean? 2.1.0 Performance: App Completeness Guideline 2.1 - Performance - App Completeness Submissions to App Review, including apps you make available for pre-order, should be final versions with all necessary metadata and fully functional URLs included; placeholder text, empty websites, and other temporary content should be scrubbed before submission. Make sure your app has been tested on-device for bugs and stability before you submit it, and include demo account info (and turn on your back-end service!) if your app includes a login. If you are unable to provide a demo account due to legal or security obligations, you may include a built-in demo mode in lieu of a demo account with prior approval by Apple. Ensure the demo mode exhibits your app’s full features and functionality. We will reject incomplete app bundles and binaries that crash or exhibit obvious technical problems. Issue Description The app exhibited one or more bugs that would negatively impact App Store users. Bug description: your app displayed an error message when we used Sign in with Apple and did not proceed. Review device details: Device type: Apple Watch OS version: watchOS 10.5 Next Steps Test the app on supported devices to identify and resolve bugs and stability issues before submitting for review. If the bug cannot be reproduced, try the following: For new apps, uninstall all previous versions of the app from a device, then install and follow the steps to reproduce. For app updates, install the new version as an update to the previous version, then follow the steps to reproduce. Resources For information about testing apps and preparing them for review, see Testing a Release Build. To learn about troubleshooting networking issues, see Networking Overview.
0
0
455
Sep ’24
Apple Watch Crash - iOS 18
Hello everyone, I really need your help here :-)) iOS App. 17 and up. Widget extensions and watchOS app as well. New build for iOS 18 earlier this week. All platforms works perfect, except the Apple Watch version, which crash constantly on launch. Testing on simulator and testing devices - works perfect. Uploading to TestFlight and running on the same device - crash. The only thing I see in the crash report is StoredLocationBased.get error. It takes me to nowhere inside the project. Opened a DTS to Apple as well. Any help here will be fully appreciated. Thank you so much!
1
0
428
Sep ’24