Send a notification to an Apple Watch extension

I have an iPhone 8.2 app that pairs with a bluetooth accessory in the background (I have enabled it in the capabilities tab). Whenever I receive a message from an accessory (included with the iPhone), I would like to send a notification to the Apple Watch extension (so that the user can visualize the updated state of the accessory).

How can i do this?


Additional subheadings :

  • Ideally, I would like the user to see the notification as well if Apple View an app extension in the background ( question 2: can an apple extend hours in the background?).
  • I'm also not sure if I can send a notification without accessing this Apple Viewer app. Question 3: Is this possible?
+3


source to share


2 answers


You can send this notification using MMWormhole .

You send it using:

[self.wormhole passMessageObject:@{@"titleString" : title} 
                      identifier:@"messageIdentifier"];

      

and you get it using:



[self.wormhole listenForMessageWithIdentifier:@"messageIdentifier" 
 listener:^(id messageObject) {
    // Do Something
}];

      

Note that the wormhole uses app groups to communicate, so you need to enable it.

What MMWormhole uses under the hood, CFNotificationCenterGetDarwinNotifyCenter

and you have more info on that in this middle position post .

As far as the subqueries are concerned, I'm afraid I don't have 100% defined, but I believe that yes, you also extend the apple view time in the background. As for the third question, I didn't understand it.

+4


source


Update for iOS 9.0 and higher.

While MMWormhole also runs on watchOS 2, it would be preferable to use the Apple WatchConnectivity framework on watchOS 2.0 and above. MMWormhole requires the use of application groups, it WatchConnectivity

doesn't. WatchConnectivity

really requires iOS 9.0 and up.

Below is a quick example of how to send a simple one String

from an iOS app to a WatchKit extension. First, let's create a helper class.

class WatchConnectivityPhoneHelper : NSObject, WCSessionDelegate
{
    static let sharedInstance:WatchConnectivityPhoneHelper = WatchConnectivityPhoneHelper()

    let theSession:WCSession = WCSession.defaultSession()

    override init()
    {
        super.init()

        // Set the delegate of the WCSession
        theSession.delegate = self

        // Activate the session so that it will start receiving delegate callbacks
        theSession.activateSession()
    }

    // Used solely to initialize the singleton for the class, which calls the constructor and activates the event listeners
    func start()
    {

    }

    // Both apps must be active to send a message
    func sendStringToWatch(message:String, callback:[String : AnyObject] -> ())
    {
        // Send the message to the Watch
        theSession.sendMessage(["testString" : message], replyHandler:
        { (reply: [String : AnyObject]) -> Void in
            // Handle the reply here

            // Send the reply in the callback
            callback(reply)
        },
        errorHandler:
        { (error:NSError) -> Void in
            // Handle the error here

        })
    }

    // A message was sent by the Watch and received by the iOS app. This does NOT handle replies to messages sent from the iOS app
    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)
    {
        // Handle received message logic here

        if (message["testString"] != nil)
        {
            replyHandler(["testString" : "Received Message!"])
        }
    }
}

      

This helper class will be nearly identical to the WatchKit extension. I named the WatchKit Extension version of this class WatchConnectivityExtensionHelper

. I won't embed it because, again, it's roughly identical to the helper class above.

Using

We need to start iOS and WatchKit accessibility message listeners by instantiating the helper class. All we need to do is call some function or refer to some variable in the singlelet to initialize it. Otherwise, iOS or the WatchKit extension will send messages and others may not receive them.



iOS - AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
    {
        // Start the event listener for communications between the iOS app and the Apple Watch
        WatchConnectivityPhoneHelper.sharedInstance().start()

        ...
    }

    ...
}

      

WatchKit Extension - ExtensionDelegate.swift

class ExtensionDelegate: NSObject, WKExtensionDelegate
{
    func applicationDidFinishLaunching()
    {
        // Start the event listener for communications between the iOS app and the Apple Watch
        WatchConnectivityExtensionHelper.sharedInstance.start()

        ...
    }

    ...
}

      

Then, anywhere in the iOS app, call sendStringToWatch

to send String

to the WatchKit extension:

WatchConnectivityPhoneHelper.sharedInstance.sendStringToWatch("Test message!")
{ (reply:[String : AnyObject]) -> Void in
    if (reply["testString"] != nil)
    {
        let receivedString:String = reply["testString"] as! String

        print(receivedString)
    }
}

      

0


source







All Articles