WKWatchConnectivityRefreshBackgroundTask example

2019-09-14 09:15发布

I want to pass data from my iOS App to my watchOS 3 app using WKWatchConnectivityRefreshBackgroundTask

How do I set up code in my watchOS App to handle the data being transferred?

For example in the past I used this iOS code to send a message from the iOS App and if there was no connection send a context:

func sendTable()
{
    let tableInfo: WatchWorkout = PhoneData().buildWatchTableData(Foundation.Date().refDays())
    let archivedTable: Data = NSKeyedArchiver.archivedData(withRootObject: tableInfo)
    if validSession
    {
        sendMessage([Keys.UpdateType : PhoneUpdateType.TableInfo.rawValue, Keys.Workout: archivedTable])
    }
    else
    {
        do
        {
            try updateApplicationContext([Keys.UpdateType : PhoneUpdateType.TableInfo.rawValue, Keys.Workout: archivedTable])
        }
        catch
        {
            print("Phone Session - error sending info: \(error)")
        }
    }
}


func sendMessage(_ message: [String : AnyObject], replyHandler: (([String : AnyObject]) -> Void)? = nil, errorHandler: ((NSError) -> Void)? = nil)
{
    print("Phone Session - phone sent message")
    session!.sendMessage(message,
        replyHandler:
        nil,
        errorHandler:
        {
            (error) -> Void in
            print("Phone Session - Error Message during transfer to Watch: \(error)")
        }
    )
}


func updateApplicationContext(_ applicationContext: [String : AnyObject]) throws
{
    print("Phone Session - phone sent context")
    if ((session) != nil)
    {
        do
        {
            try session!.updateApplicationContext(applicationContext)
        }
        catch let error
        {
            print("Phone Session - OPPS something wrong - context send failed")
            throw error
        }
    }
}

I'm not sure how to code the receipt of this data as a background task on the watch.

Can someone provide some example code or post a link? The only Apple example code is not very helpful: https://developer.apple.com/library/prerelease/content/samplecode/WatchBackgroundRefresh/Introduction/Intro.html

Thanks

Greg

2条回答
时光不老,我们不散
2楼-- · 2019-09-14 09:15

The Quick Switch sample code was updated together with the release of watchOS 3 to include an example of handling the WatchConnectivity background refresh task.

查看更多
迷人小祖宗
3楼-- · 2019-09-14 09:29

@ccjensen The Quick Switch sample code doesn't work, is it? It will crash on my iPhone6 iOS10.0 beta3. I sent feedback already last Friday.

In my Case, calling updateApplicationContext(_:) transferUserInfo(_:) transferCurrentComplicationUserInfo(_:) transferFile(_:metadata:) on iPhone side never trigger handle(_:) listener.

查看更多
登录 后发表回答