Objective-C WatchOS send a text message - ios

I have an iphone app that sends a text message. And now I have started to make an Apple Watch version of this app.
When I try to import <MessageUI/MessageUI.h> it says its not found. I have been doing some reading and found out that MessageUI is not an available framework for watchOS, but I found that you can use non-supported frameworks using WatchConnectivity. My issue is all the examples I found are in swift and I am using Objective-C, my question is how do I use WatchConnectivity to use MessageUI and/or is there another way to send a text message via watchOS?

No you cannot send a text message via watchOS directly , we don't have MessageUI framework support in it. However, using WatchConnectivity send the text of message from Watch to iPhone and then on phone do the rest. But there is a limitation in the case when app is in background and message is received from watch.
On Watch
if([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
[session sendMessage:[NSDictionary dictionaryWithObject:#"message text here" forKey:#"text"]
replyHandler:^(NSDictionary *reply) {
//handle reply from iPhone app here
}
errorHandler:^(NSError *error) {
//catch any errors here
}];
}
On iPhone
- (void)session:(nonnull WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * __nonnull))replyHandler {
//--Message UI code here
}
Available System Technologies for WatchOS2

Related

sessionReachabilityDidChange not called on watch

I would like to have my watch app respond to the parent app on the phone being killed. When the watch app is running and the phone app is killed I get no callback from either sessionReachabilityDidChange or sessionWatchStateDidChange. Based on apple documentation:
This method is called to let the current process know that its
counterpart session’s reachability changed.
So, it seems that I should get a callback. I've set the WCSession delegate to my class on the watch. The session on the watch receives callbacks for application context. Why am i not getting a reachability callback?
Code Below..
+ (SomeClass *)sharedInstance {
static dispatch_once_t pred;
static SomeClass *shared = nil;
dispatch_once(&pred, ^{
shared = [[SomeClass alloc] init];
[Model sharedInstance].delegate = shared;
});
return shared;
}
#pragma mark - setup
- (void)initializeSession {
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
[self sync];
}
}
-(BOOL) hasValidWCSession {
return ([WCSession isSupported] && [WCSession defaultSession].isReachable);
}
#pragma mark - WCSessionDelegate
- (void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *, id> *)applicationContext {
NSLog(#"application context received on watch: %#", applicationContext);
[[Model sharedInstance] process:applicationContext];
}
- (void)sessionWatchStateDidChange:(WCSession *)session {
NSLog(#"wcession state changed on watch");
}
- (void)sessionReachabilityDidChange:(WCSession *)session {
NSLog(#"wcsession reachability changed on watch");
}
The iPhone app counterpart does not need to be running in order for reachable to be true from the perspective of the Apple Watch app. If the iPhone itself is paired and reachable, sending messages using WCSession from the watch app will launch the iPhone app in the background.
Thus, I would not expect sessionReachabilityDidChange: to be called on the watch app when the iOS app is killed. This also means that your iPhone app should be prepared to be launched in the background at any time, and activate WCSession promptly, to handle incoming requests from the watch app (similar to how certain push notifications, etc., can launch an iOS app).
However, from the perspective of the iPhone app, the watch app counterpart is only considered reachable when "a paired and active Apple Watch is in range and the associated Watch app is running in the foreground" (documentation).
Also, note that sessionWatchStateDidChange: is invoked when "the value in the paired, watchAppInstalled, complicationEnabled, or watchDirectoryURL properties of the WCSession object changes".

WCSession is never paired or installed on Apple Watch

I have been trying to use WCSession on WatchKit 2.0 and iOS 9 but it does not seem to work.
I keep getting the same error message:
Error Domain=WCErrorDomain Code=7005 "Device is not paired." UserInfo={NSLocalizedDescription=Device is not paired., NSLocalizedRecoverySuggestion=Pair the device with a Watch.}
In the App Watch Interface I added WCSessionDelegate and in awakeWithContext: initialize the session like this:
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
In the iOS app I added WCSessionDelegate and initialized in application: didFinishLaunchingWithOptions: the same way but it is never paired on either location.
The Apple Watch IS Paired it just does not work with WCSession
And when I call the following I got the error.
[session sendMessage:userInfo replyHandler:^(NSDictionary *reply) {
NSLog(#"AW open parent: Done");
}
errorHandler:^(NSError *error) {
NSLog(#"AW open parent ERROR: %#",error.description);
}
];
Any ideas what is going on?
UPDATE:
I restarted all devices + Xcode
Apple Watch is 100% paired
Delegates are set and session is activated
iOS app does not starts at all but it works more or less with openParentApplication: reply: (The app supposed to do some heavy lifting but it terminates the app in the middle of it even though it is beginBackgroundTask is used)

ERROR: "Message reply took too long" sending message to device Watch kit OS 2

Im getting the following error when sending a message from Apple Watch to device
Error Domain=WCErrorDomain Code=7012 "Message reply took too long."
UserInfo={NSLocalizedDescription=Message reply took too long.,
NSLocalizedFailureReason=Reply timeout occured.}
#import <WatchConnectivity/WatchConnectivity.h> is in both watch and main app targets, and conforms to delegate methods on both watch and device
SEND MESSAGE FROM WATCH TO DEVICE
Session confirmed as Available
Session confirmed as Reachable
NSDictionary *applicationDict = [[NSDictionary alloc] initWithObjects:#[#"SomethingHere"] forKeys:#[#"valueKey"]];
if([[WCSession defaultSession] isReachable]) {
NSLog(#"Reachable"); //<---- Console shows reachable
[[WCSession defaultSession] sendMessage:applicationDict
replyHandler:^(NSDictionary *reply) {
NSLog(#"%#",reply);
}
errorHandler:^(NSError *error) {
NSLog(#"%#",error); //<--- returns error
}];
}
DEVICE
In appdelegate didFinishLaunching
// Watch kit session
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
NSLog(#"\n\n - WatchKit Session Started - \n\n");
}
else{
NSLog(#"WatchKit Session Error");
}
Session confirmed as starting as expected
Receiving Message On Device
- (void)session:(nonnull WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * __nonnull))replyHandler {
NSLog(#"Data delagte");
dispatch_async(dispatch_get_main_queue(), ^{
resultFromWatch = [message objectForKey:#"resultDataValue"];
});
}
Update:
- (void) session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)message {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
Stops the error message received as per ccjensen comment
Check these things:
1/ Make sure to implement the WCSessionDelegate properly on the phone side. (No idea if and/or how much you implemented so far)
In particular, make sure you implemented session(_:didReceiveMessage:replyHandler:).
2/ Make sure that you actually call the replyHandler in the WCSessionDelegate as highlighted in the doc: "You must execute the reply block as part of your implementation." WCSessionDelegate Protocol Reference
3/ Once you've checked these, make sur you run the latest version of the iPhone app before re-trying with the watch.
If these don't work, then it means your WCSessionDelegate implementation is too slow and therefore times out or you get a good old fashion network issue between the watch and the phone (unlikely in the sim, but bugs are possible).
Hope this helps.
Edit:
I missed to mention, that the counter part app must be active for it to respond. It means, the iPhone app must be at least in the background (launched once) for it to respond.
If it isn't, and after a while you will get a timeout.
Make sure you set WCSession delegate before you active the session.

transferCurrentComplicationUserInfo and ComplicationController

I'm looking to send data to my complication as part of a didReceiveRemoteNotification to update the data displayed but there seems to be little documentation from Apple on how to setup the relationship between this and the complication itself.
When a ComplicationController is created, am I supposed to create a WCSession as well and begin listening for the delegate calls? I'm managed to place it into getPlaceholderTemplateForComplication and this seems to work when the iOS application is running but not when the app has been killed (or no longer running).
I'm curious if anyone has a good guide for getting data to the watch as part of a remote JSON push notification when the iOS app is running or not.
I'd recommend watching the WatchConnectivity session from WWDC as it covers updating complications quite a bit towards the end.
In summary, in the iOS app once you have the contents to send:
NSDictionary *userInfo = // data to send
[[WCSession defaultSession] transferComplicationUserInfo:userInfo];
...
- (void)session:(WCSession * __nonnull)session didFinishUserInfoTransfer:(WCSessionUserInfoTransfer *)userInfoTransfer error:(nullable NSError *)error {
// handle error
NSLog(#"%s %# (%#)", __PRETTY_FUNCTION__, userInfoTransfer, error);
}
and on the watch side:
#property WCSession *session;
...
_session = [WCSession defaultSession];
_session.delegate = self;
[_session activateSession];
...
- (void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *, id> *)userInfo {
// persist data and trigger reload/extend of complication(s)
}

How to send data from Iphone to Apple Watch in OS2 in Objective-C

I've seen a similar question posted on how to send data back and forth in Swift. I'm asking the same question but in Objective-C. I've also viewed Apple's transition docs.
I work best with clear examples, rather than lecture material. So if someone has implemented this and wouldn't mind sharing, that would be much appreciated.
Here´s a link to a Q/A about WatchConnectivity: Send messages between iOS and WatchOS with WatchConnectivity in watchOS2
I will give you an example go ApplicationContext, there are 2 other messaging techniques with WatchConnectivity. Please watch WWDC2015 session video for those.
First you need to conform to the WCSessionDelegate protocol in the classes you want to send and receive data from/to. E.g both on watch and iPhone.
Basic checking before: (this is just an example, implement better than this)
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
NSLog(#"SESSION AVAIBLE");
}
//Objective-C
if ([[WCSession defaultSession] isReachable]) {
NSLog(#"SESSION REACHABLE");
}
This will send the data from the phone to the watch.
WCSession *session = [WCSession defaultSession];
NSError *error;
[session updateApplicationContext:#{#"firstItem": #"item1", #"secondItem":[NSNumber numberWithInt:2]} error:&error];
This will receive the data from the phone on the watch.
- (void) session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {
NSLog(#"%#", applicationContext);
item1 = [applicationContext objectForKey:#"firstItem"];
item2 = [[applicationContext objectForKey:#"secondItem"] intValue];
}
The WWDC2015 video on WatchConnectivity is really great, I recommend to check it out.

Resources