Watch Connectivity

RSS for tag

Implement two-way communication between an iOS app and its paired watchOS app using Watch Connectivity.

Posts under Watch Connectivity tag

55 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Bring iOS app to foreground from Apple Watch app
Exploring Live Activity feature for Apple Watch right now and found that it has this default view with "Open on iPhone" button when you tap Live Activity. That button perfectly brings iOS app to foreground as if you tapped iOS's Live Activity. Is there a way to mimic that behavior from inside Watch app code? From inside WKApplicationDelegate, for example Tried openSystemURL but it seems lile it's only available for tel or sms links
1
0
87
2d
Standalone watch app design/approach for kids/family/shared watches paired with parents' phones
Hi, so, we grabbed a couple of nice new watches the other week (Ultra for dad, SE for teenage son). Mostly cool and working together (calls, messages, maps, walkie talkies, etc, etc). All good. But then son said, "Dad, why can't I see my sleep stuff like you can..?". He was right, it wasn't working. Looking around a bit, it turns out that there are a bunch of things that are turned off or not available when pairing a kids watch with dad's phone. From the Apple page: "The following features and apps are not available: Medications, respiratory rate, irregular heart rhythm notifications, ECG, AF History, Cycle Tracking, Sleep, Wrist Temperature, Blood Oxygen, Walking Steadiness, Audiobooks, Remote, News, Shortcuts and the double-tap gesture". Now dev-me reacts to this situation with: "Ok, so let's just build a little standalone sleep app for son's watch. There must be lots of parents out there who would like the same thing". And there are also a bunch of other "family sharing" enabled apps that when you try and use them on kid's phone, say "iPhone requireed", i.e, they don't apparently work with just a watch hooked up to mum or dad's phone. So before I dive into that kind of project, which seems like an obvious fix path from a dev and a parents' point of view: does anybody know if this from Apple's point of view is a hardware, a software or a legal/age limitation? What's the basic framework/dev/design issue here? Is it something on the device(s) that prevents sleep data from even being collected on family/kids paired watches? (Therefore don't bother trying to build an app); I assume not becauses it's just a normal SE used by a kid; or Is it "just" that Apple hasn't wanted to make that available without a kids iPhone too (Therefore you could certainly build a standalone app to do what Apple hasn't wanted to do); or Netiher 1 nor 2, but Apple won't even allow Sleep data collection for kids for some legal/health data reason (Therefore don't bother trying to build the app).
0
1
156
3w
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 -> [String: Any] { return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<[String: Any], Error>) 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
360
Oct ’24
I can't unlock my MacBook Pro M1 using OS 15 and 15.1
I started a thread stating the above and apparently I am not the only one to encounter this issue. My Apple Watch is the version 10 and I certainly didn't expect to have this problem. My older Apple Watch did have this same problem initially but after a few updated it stated working. I only tried the consumer beta hoping the issue was resolved. One of the posts today hoped the next update would fix it and I informed him I had installed the beta and it still wasn't working.
2
0
254
Oct ’24
Bugs in iOS 18
I was using iOS 18.1 beta 3 Developer Version in my iPhone 15 Pro max and during the time of apple launch event, Apps in my phone started crashing. When I restarted my iPhone it froze on Apple Logo Screen and kept rebooting from there. I can consider this as a coincidence but i am unable to restore phone to same version or iOS 18 RC. Now another surprise from last couple of days my airPods Pro are behaving strange, one of the buds doesn’t work many times and even when connected to iPhone it shows just one of the buds but later fixes it automatically. Now one more surprise since last might my iWatch 8 which is also on beta version has stopped charging. is anyone else facing the same issue ?
0
0
2.1k
Sep ’24
WatchConnectivity: Sending from Watch (in audio background mode) -> iPhone (backgrounded) not working
Hi, I have an app that is performing long-duration audio recording on the Watch and need to communicate with the phone occasionally to: Request an auth token (login happens on the phone app) when needing to upload a recording. Occasionally poke the iPhone app to sample the current location (I don't do this on Watch). Most of the time, both the Watch and iPhone apps would be backgrounded but the Watch app has background audio enabled and is recording, so processing continues. I'm finding that WatchConnectivity isn't connected to the phone in these cases and cannot send a ping. That is, on the Watch side, WatchConnectivity is not connected to the phone (isReachable==false), and the messages are simply never received on the phone as a result. I'm not sure how else the apps should communicate this information. How are these scenarios typically handled? Thank you, -- B.
0
0
334
Aug ’24
Integrating Apple Watch Health Data with Vision Pro
Hi everyone, I have a question regarding the integration of Apple Watch and Vision Pro. Is it possible to connect an Apple Watch to Vision Pro to access health data and display it within Vision Pro applications? If so, could you provide some guidance or point me towards relevant resources or APIs that would help in achieving this? Thank you in advance for your assistance!
4
0
488
Aug ’24
Updating watchOS complication when data in iOS app changes.
Hello, I'm facing problems when attempting to update my watchOS complication when relevant data on the iPhone app changes. From what I gather reading the documentation I have to use the Watch Connectivity Framework to send said new data from the phone to the watch: use transferCurrentComplicationUserInfo() to send a dictionary of data from the phone to the watch implement the didReceiveUserInfo delegate method to handle incoming data on the watch in said handler, save the incoming data to UserDefaults using an App Group so the widget-extension can read that data after saving the data to UserDefaults, call WidgetCenter.shared.reloadAllTimelines() so watchOS can request fresh timelines for my complications change the getTimeline() method of my TimelineProvider so it uses the received data from UserDefaults OR async fetch fresh data if received data from phone is too old If I understand correctly, transferCurrentComplicationUserInfo() is limited to be used a maximum of 50 times a day. I'm running the apps in debug mode, so this should be no problem. Here is my current implementation: 1 : Setup of my WC class: final class Connectivity: NSObject { // singleton approach static let shared = Connectivity() // used to rate limit transmissions from phone → watch private var lastSentBalanceContext: Date? = nil private override init() { super.init() // no need to check availability on watchOS #if !os(watchOS) guard WCSession.isSupported() else { return } #endif WCSession.default.delegate = self WCSession.default.activate() } } 2 : The method enabling transmission from phone to watch: #if os(iOS) extension Connectivity: WCSessionDelegate { func sendBalanceContext(sample: HealthData) { guard WCSession.default.activationState == .activated else { return } guard WCSession.default.isWatchAppInstalled else { return } // rate limitat transmissions guard self.lastSentBalanceContext == nil || abs(Date.now.timeIntervalSince(self.lastSentBalanceContext!)) > 10 else { return } if WCSession.default.remainingComplicationUserInfoTransfers > 0 { WCSession.default.transferCurrentComplicationUserInfo([ "context": "balance", "date": sample.date, "burnedActive": sample.burnedActive, // more data... ]) self.lastSentBalanceContext = .now } } // boilerplate handlers here } #endif 3 : Delegete method that handles incoming data on the watch: #if os(watchOS) extension Connectivity: WCSessionDelegate { func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) { guard let context = userInfo["context"] as? String, context == "balance" else { return } guard let date = userInfo["date"] as? Date, let burnedActive = userInfo["burnedActive"] as? Int /* more data... */ else { return } guard let SharedDefaults = UserDefaults(suiteName: "group.4DXABR577J.com.count.kcal.app") else { return } // TimelineProvider uses this to determine wether to use this data or fetch data on its own SharedDefaults.set(Date.now, forKey: "lastReceivedBalanceContext") SharedDefaults.set(date, forKey: "date") SharedDefaults.set(burnedActive, forKey: "burnedActive") // more data... WidgetCenter.shared.reloadAllTimelines() } // boilerplate handlers } #endif 4 : Finally, the TimelineProvider: struct HealthDataEntry: TimelineEntry { let date: Date let data: HealthData } struct HealthDataTimelineProvider: TimelineProvider { // other callbacks here func getTimeline(in context: Context, completion: @escaping (Timeline<HealthDataEntry>) -> Void) { let SharedDefaults: UserDefaults = UserDefaults(suiteName: "group.4DXABR577J.com.count.kcal.app")! let nextUpdateDate = Calendar.current.date(byAdding: .minute, value: 15, to: .now)! // use data from phone if it is less than 60 seconds old if let lastReceivedBalanceContext = SharedDefaults.object(forKey: "lastReceivedBalanceContext") as? Date { let interval = lastReceivedBalanceContext.timeIntervalSince(.now) if interval > -60 && interval <= 0 { let data = HealthData(date: SharedDefaults.object(forKey: "date") as? Date ?? Date(timeIntervalSinceReferenceDate: 0), burnedActive: SharedDefaults.integer(forKey: "burnedActive"), burnedActive7: SharedDefaults.integer(forKey: "burnedActive7") /* other data ... */) let timeline = Timeline( entries: [HealthDataEntry(date: .now, data: data)], policy: .after(nextUpdateDate) ) completion(timeline) return } } // default: fetch from HealthKit (if received data from phone is > 60s) Task { let timeline = Timeline( entries: [HealthDataEntry(date: .now, data: try! await asyncFetchData())], policy: .after(nextUpdateDate) ) completion(timeline) } } } The issue I am facing is that the watchOS complication only gets refreshed when I acitvely build and run the watchOS app in Xcode and then initiate a transmission of data to the watch. This works even if I do it back to back to back. As soon as I stop the watchOS app from within Xcode, my complications won't update anymore. I noticed this behavior when I used print() statements throughout my code to see whether it is beeing executed as expected. The iPhone sends data, the watch receives it but then the watch fails to update the complications ONLY when not running from Xcode. Can you spot any flaws in my implementation or in my understanding? Maybe transferCurrentComplicationUserInfo() just isn't as reliable as I think it should be? I interpreted it as being practically guaranteed to refresh the complications 50 times a day, pretty much instantly? Any help or guidance would be greatly appreciated!
1
0
832
Jul ’24
WatchConnectivity Session becomes unreachable but shouldn't
So for context I am building an app where the Apple Watch establishes a WatchConnectivity session with the parent iPhone app and streams audio data from the watch Mic to the iPhone for processing on Deepgram to perform STT. This works very well, unless I tilt my wrist and the display goes to sleep. What I find strange is that due to the mic being in use on my watch, the app is still showing on the always on display and is still trying to send the audio data to my phone in the background (which is perfect!) but the iPhone does not seem to be responding. So my watch code is: private func sendData(_ data: Data) { let dict: [String: Any] = ["audioData": data] session.sendMessage(dict, replyHandler: nil, errorHandler: { error in print("Failed to send data: \(error.localizedDescription)") }) } and my Xcode logs Failed to send data: WatchConnectivity session on paired device is not reachable. So the watch is still running the process but because session.isReachable is false the audio data is not sent which it should be! Is there any way to keep the connection established and data sharing when the display dims?
0
0
469
Jul ’24
Trigger data transfer from watchOS when connectivity is restored
Hello, I have an iOS app and a companion watchOS app. Users record a workout on Apple Watch, the data for which is then transferred using both Watch Connectivity and Core Data + CloudKit (NSPersistentCloudKitContainer) to their iPhone, where it is processed and displayed. As users are recording the workout on their Apple Watch, when they finish and the transfer begins, their iPhone is often not reachable to immediately send the data using Watch Connectivity and they have no network connection (cellular or Wi-Fi). With Watch Connectivity I use transferFile from WCSession, which queues the file for transfer. With Core Data + Cloudkit I save the data and the export is queued. An undetermined amount of time may pass until the user returns to their iPhone or connects to Wi-Fi and most of the time neither of the transfer methods actually transfers the data until the user opens the watchOS app into the foreground, at which point the transfer happens immediately for both methods. I've tried a number of things already, without success, such as: Using sendMessage from WCSession to send an immediate message to the watchOS app when the iOS app returns to the foreground to try and wake the watchOS app up so it can complete the data transfer. On the watchOS app, after attempting to transfer the data, using downloadTask from URLSession to queue a background task to download something, in the hope that it would wake the watchOS app when network connectivity was restored and enable it to complete the data transfer. On the watchOS app, instead of saving the data using NSPersistentCloudKitContainer, using CKRecord and CKDatabase directly to save the data using userInitiated as the quality of service, in the hope that it would be exported once network connectivity was restored. Is there a way to trigger the watchOS app to transfer the data using Watch Connectivity or Core Data + CloudKit in the background when reachabillity or network connectivity is restored, even if the app may have been suspended by watchOS? Many Thanks, Alex
1
0
608
Jul ’24
7014 - Payload could not be delivered.
Hi All, can anyone help me to the below issue? i used the WatchConnectivity to send data from iphone to watch app. Now i tried to run them on emulator (watch series 5, and iphone 15 pro) I have an error when i tried to send message data from iphone app (react-native) to watch app: { "code": "EWCERRORDOMAIN7014", "domain": "WCErrorDomain", "message": "Payload could not be delivered.", "nativeStackIOS": [ "0 releasev2 0x0000000101979c90 RCTJSErrorFromCodeMessageAndNSError + 112", "1 releasev2 0x0000000101979bd0 RCTJSErrorFromNSError + 256", "2 releasev2 0x000000010190c2b4 __41-[RCTModuleMethod processMethodSignature]_block_invoke_4.110 + 148", "3 releasev2 0x000000010185003d __35-[RNWatch sendMessage:reply:error:]_block_invoke.116 + 77", "4 WatchConnectivity 0x000000011428b176 __70-[WCSession _onqueue_notifyOfMessageError:messageID:withErrorHandler:]_block_invoke + 206", "5 Foundation 0x0000000119095004 NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK + 7", "6 Foundation 0x0000000119094f02 -[NSBlockOperation main] + 94", "7 Foundation 0x0000000119097ef2 NSOPERATION_IS_INVOKING_MAIN + 17", "8 Foundation 0x00000001190940aa -[NSOperation start] + 730", "9 Foundation 0x0000000119098744 NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION + 17", "10 Foundation 0x0000000119098385 __NSOQSchedule_f + 182", "11 libdispatch.dylib 0x000000011434ca90 _dispatch_call_block_and_release + 12", "12 libdispatch.dylib 0x000000011434dd3a _dispatch_client_callout + 8", "13 libdispatch.dylib 0x000000011435126a _dispatch_continuation_pop + 874", "14 libdispatch.dylib 0x00000001143502b0 _dispatch_async_redirect_invoke + 994", "15 libdispatch.dylib 0x000000011436041e _dispatch_root_queue_drain + 372", "16 libdispatch.dylib 0x0000000114360e88 _dispatch_worker_thread2 + 244", "17 libsystem_pthread.dylib 0x0000000116800c0f _pthread_wqthread + 257", "18 libsystem_pthread.dylib 0x00000001167ffbbf start_wqthread + 15" ], "userInfo": { "NSLocalizedDescription": "Payload could not be delivered." } } Here is the class connector shared data on watch target: class SharedDataConnecter: NSObject, ObservableObject { var session: WCSession init(session: WCSession = .default){ self.session = session super.init() if WCSession.isSupported(){ session.delegate = self session.activate() } } } extension SharedDataConnecter: WCSessionDelegate{ func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { print("Active State: ", activationState.rawValue) print("Error: ", error) } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { print("AAAA message from app: ", message) } }
0
0
547
Jun ’24
A case against TN3135 WatchOS restrictions (NWPathMonitor)
REF: TN3135 Context: Stand alone watch app Target platform is cellular watch Phone likely (90%) out of range in a different location (although this applies equally to watch+phone too) User story: As a water & wind sports enthusiast who is either in-shore, near-shore or off-shore I want to receive near-real-time wind reports on my wrist so that I can determine ...(many varieties of facts) My Case for lifting restrictions on NWPathMonitor, NWPath, NWPath.Status What this is about: Proactive UX (enlightening) vs. Reactive UX (disappointing) Reducing unnecessary code execution proactively Exactly the same purpose the tiny red x at the top center of the Watch screen serves (notifies me that the watch is offline -- probably using NWPath.Status of .unsatisfied) What this is NOT about Preflighting requests UI design (although there is a UI component associated with UX - like the tiny red x ...) Establishing low level connections Watch App End User Scenario Water & Wind sports enthusiasts are frequently in and out of cellular range. As a kiteboarding enthusiast I am relating my personal experience. The phone is in the vehicle in the parking lot > 100 yards away while I'm standing on the beach (before I get into the water). On shore or just off shore my watch likely has a solid connection. When 100 yards off shore watch has a decently but tenuous connection. While at 200 yards off shore watch has no connection at all. Developer's Case Current REACTIVE solution My current watch app is forced to be reactive by attempting a URLSession request and capturing one of the plethora of URLError error conditions. This action, of course, is activated through a user interaction workflow: User interaction --> create URL --> use URLSession --> capture URLError --> determine failure cause --> notify user network data cannot be retrieved Optimal PROACTIVE solution Provide a simple indicator to the end user that the data cannot be retrieved. The reason is not relevant to the end user, but they know their interaction with the app is unnecessary. The app's UX has been improved by proactively precluding an unnecessary interaction and precluding unecessary code execution behind the scenes. NWPath.Status = .unsatisfied --> UI shows "no network" type indicator --> (no user interaction - no backend requests - no code execution) --> NWPath.Status = .satisfied --> UI shows nominal status --> end user interacts normally Rationale Using NWPath.Status allows us as developers to fulfill some basic tenets of the Human Interface Guidelines associated with Providing Feedback Specifically, the overview states we should communicate: The current status of something A warning about an action that can have negative consequences And quoting about my specific use case, the guidelines continue: ... it often works well to display status information in a passive way so that people can view it when they need it. Consider integrating status feedback into your interface. Show people when a command can’t be carried out and help them understand why. And finally, the guideline specifically calls out the WatchOS experience I am attempting to avoid. By proactively providing feedback we can prevent the reactive "touch --> wait & see --> then disappoint with no connection" approach. Final Thoughts I realize I am naive about the behind the scenes with this API. I realize that this is likely not the intended use of this API. But as a developer, I also realize users of our stuff often use it in ways we never intended. Please allow these API features on WatchOS
9
1
815
Jun ’24
Xcode can not consistently connect with WatchOS
When testing my single target watchOS app, I can at best get about one minute of connect time after installing my app on my Apple Watch Series 4. After about a minute or less, Xcode loses it connection to the watch and it becomes disconnected. When attempting to reconnect it gets transport errors. I can restart my Mac and reconnect again, but again only for about a minute before the transport error occurs again. I'm using Xcode 15.4 on a MacOS 14.5 and a Apple Watch Series 4 running 10.5
2
0
563
Jun ’24
File transfer to watch fails after OS update
When transferring files from iPhone to Watch, if you run the app and try to transfer after updating the OS, the transfer may not be possible. (or transmission seems to be too slow) Just completely close the app, restart it, and try again. Does anyone know the cause or solution to this problem? It happened after the last 17.5 update and today after the 17.5.1 update. The app doesn't crash or anything, and it doesn't happen often, so I didn't send any feedback or anything, but it's strange.
3
0
832
Jun ’24
Is it possible to change bundle id of Watch kit app?
Long story short, I had my App and Watch app already uploaded to the app store. However, I needed to add a WatchConnectivity to have App to Watch communication. At the beginning My app bundle id was: com.x My watch bundle id was: com.x.watchkitapp However, while developing Watch Connectivity, I noticed that my Apps are not connected unless I changed it to com.x.watchkitapp -> com.x.watch However after changing it I cannot submit my bundle anymore. I'm getting Asset validation failed error Invalid Bundle Identifier. Attempting to change bundle identifier from com.x.watchkitapp to com.x.watch is disallowed for bundle x.app/Watch/WatchX Watch App.app. (ID: 75a4621a-7e28-411d-a2a7-84674e460656) Any ideas how this could be solved?
1
0
567
May ’24
Get rid of the task time displayed by the system
When I run my app in debug mode, whenever a time consuming task is run (like a core data fetch request) there is a time indication appearing on top of the view. I am unable to find the meaning of this and how it is named. It looks like: "appName NNNN ms" (it is not caught by the screen shot) Can someone tell if it is possible to get rid of it and how ? Thanks for your help !
1
0
643
May ’24