Lachtan
Lachtan

Reputation: 5172

How trigger background process from Watch on iPhone (trigger: Watch)?

I'd like to add to my Watch app functionality which send to iPhone app a Local Notification (while iPhone app is on the background or iPhone is locked).

I know how to create Local Notification itself.

What Im asking for is way, how to trigger background process (which contains also Local Notification) on iPhone by (for example) tapping on button on Apple Watch.

Upvotes: 0

Views: 479

Answers (2)

Lachtan
Lachtan

Reputation: 5172

Code in my InterfaceController.swift:

    @IBAction func btn() {

    sendMessageToParentApp("Button tapped")

}

// METHODS #2:

func sendMessageToParentApp (input:String) {

    let dictionary = ["message":input]

    WKInterfaceController.openParentApplication(dictionary, reply: { (replyDictionary, error) -> Void in

        if let castedResponseDictionary = replyDictionary as? [String:String], responseMessage = castedResponseDictionary["message"] {

            println(responseMessage)
            self.lbl.setText(responseMessage)

        }

    })

}

Next i made new method in my AppDelegate.swift:

    func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {

    if let infoDictionary = userInfo as? [String:String], message = infoDictionary["message"] {

        let response = "iPhone has seen this message."    // odešle se string obsahující message (tedy ten String)
        let responseDictionary = ["message":response]   // tohle zase vyrobí slovník "message":String

        NSNotificationCenter.defaultCenter().postNotificationName(notificationWatch, object: nil)

        reply(responseDictionary)

    }

}

As you can see I use Notification to get iOS app know that button has been tapped. In ViewController.swift I have Notification Observer and function which is executed every time observer catch notification that user tapped on button on watch ("notificationWatch" is global variable with notification key). Hope this will help to anybody.

Upvotes: 1

zisoft
zisoft

Reputation: 23078

WKInterfaceController.openParentApplication is the official way to communicate with the iPhone. Documentation.

You pass parameters in the userInfo dictionary and retrieve results via the reply block.

On the iPhone the request is handled by appDelegate's handleWatchKitExtensionRequest method. Documentation

Upvotes: 3

Related Questions