apple-watch - 使用 IOS 数据更新 WatchOS2 ClockKit 并发症

标签 apple-watch watchos-2 apple-watch-complication clockkit watchconnectivity

我正在尝试使用通过 WatchConnectivity 从 IOS/iPhone 传输的数据更新 watchOS2 时钟套件并发症。

尽管进行了相当多的研究,但迄今为止未成功。我发现虽然其他帖子描述了类似的挑战(还没有解决方案)

我面临3个问题:

1) 来自 ComplicationController 的 sendMessage 似乎没有唤醒 IOS 父应用程序(而从 InterfaceController 发送的相同 sendMessage 确实唤醒了 IOS 父应用程序)

2)即使将值传输到 ComplicationController(通过 sendUserInfoToComplication 并且当 IOS 应用程序处于前台时),显示在复杂功能中的值也只是有时会更新(还没有找到模式为什么有时会/有时不会)

3) 我将“getNextRequestUpdate..”设置为 2 分钟(用于测试目的)。不过,这似乎没有任何区别。 (即使在任意时间在模拟器中也被触发,但未使用“预算”/我设置了塞子来验证)

请注意,我对 IOS/Swift 编程比较陌生。但是我看到,根据其他问题/帖子,我似乎并不是唯一一个为此苦苦挣扎的人。

这里的示例代码:

复杂功能 Controller :

//
//  ComplicationController.swift
//  IOSDataToComplication WatchKit Extension
//
//  Created by Thomas Peter on 11.10.2015.
//  Copyright © 2015 Thomas Peter. All rights reserved.
//

import ClockKit
import WatchConnectivity


class ComplicationController: NSObject, CLKComplicationDataSource, WCSessionDelegate {

    var session:WCSession!
    var text:String = "watchdefault"
    var textOld:String = ""
    var header:String = "TestHeader"

    override init(){
        super.init()
        startSession()

    }

    // MARK: - Timeline Configuration

    func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
        handler([.None])
    }

    func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
        handler(nil)
    }

    func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
        handler(nil)
    }

    func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
        handler(.ShowOnLockScreen)
    }

    // MARK: - Timeline Population

    func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
        // Call the handler with the current timeline entry

        if complication.family == .ModularLarge {

            //createData()

            let entry = self.createTimeLineEntry(text, date: NSDate())

            handler(entry)


        } else {


            handler(nil)
        }
    }


    func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
        // Call the handler with the timeline entries prior to the given date
        handler(nil)
    }

    func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
        // Call the handler with the timeline entries after to the given date
        handler(nil)
    }

    // MARK: - Update Scheduling

    func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
        // Call the handler with the date when you would next like to be given the opportunity to update your complication content
        handler(NSDate(timeIntervalSinceNow: (60 * 2)))
    }

    // MARK: - Placeholder Templates

    func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
        // This method will be called once per supported complication, and the results will be cached
        let template = CLKComplicationTemplateModularLargeStandardBody()
        template.headerTextProvider = CLKSimpleTextProvider(text: "header")
        template.body1TextProvider = CLKSimpleTextProvider(text:"defaul text")


        handler(nil)
    }

    func requestedUpdateDidBegin() {
        print("Complication update is starting")


        createData()

        let server=CLKComplicationServer.sharedInstance()

        for comp in (server.activeComplications) {
            server.reloadTimelineForComplication(comp)
            print("Timeline has been reloaded!")

        }

    }



    func requestedUpdateBudgetExhausted() {
        print("Budget exhausted")
    }


    func createTimeLineEntry(bodyText: String, date:NSDate) -> CLKComplicationTimelineEntry {

        let template = CLKComplicationTemplateModularLargeStandardBody()
        template.headerTextProvider = CLKSimpleTextProvider(text: header)
        template.body1TextProvider = CLKSimpleTextProvider(text: text)

        let entry = CLKComplicationTimelineEntry(date: date, complicationTemplate: template)
        return(entry)
    }

    func createData(){


        let applicationData = ["wake":"fromComplication"]


        session.sendMessage(applicationData, replyHandler: {(replyMessage: [String : AnyObject]) -> Void in
            // handle reply from iPhone app here

            //let answer:[String:AnyObject] = replyMessage
            self.text = replyMessage["text"] as! String
            print("complication received messagereply \(self.text)")

            }, errorHandler: {(error ) -> Void in
                // catch any errors here
                print("no reply message")


        })

        print("complication sent \(applicationData) to iOS")

    }

    func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {

        textOld = text
        text = userInfo["text"] as! String

        print("complication received userinfo \(text)")

        dispatch_async(dispatch_get_main_queue()) {

        //if text != textOld {
            self.requestedUpdateDidBegin()
        //}
        }
    }




    private func startSession(){

        if (WCSession.isSupported()) {
            session = WCSession.defaultSession()
            session.delegate = self;
            session.activateSession()
        }
    }

}

View Controller :
//
//  ViewController.swift
//  IOSDataToComplication
//
//  Created by Thomas Peter on 11.10.2015.
//  Copyright © 2015 Thomas Peter. All rights reserved.
//

import UIKit
import WatchConnectivity


class ViewController: UIViewController, WCSessionDelegate {

    var session:WCSession!

    var time:String = "default"

    var text:String = "default"




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        startSession()
        getData()
        sendUserInfoToComplication()
  }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func getData(){
        let timeValue = NSDate()
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "hh:mm"
        time = dateFormatter.stringFromDate(timeValue)

        text = "iPhone \(time)"
        print("constructed \(text)")

    }

    private func startSession(){

        if (WCSession.isSupported()) {
            session = WCSession.defaultSession()
            session.delegate = self;
            session.activateSession()
        }

        print("iPhone session started")

    }

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

        let receivedMessage = message["wake"] as! String

        print("iphone received message \(receivedMessage)")


        let applicationDict = ["text":text]

        replyHandler(applicationDict as [String : AnyObject])

        getData()

    }

    func sendUserInfoToComplication(){

        let applicationDict = ["text":text]

        session.transferCurrentComplicationUserInfo(applicationDict)
        print("iphone sent userinfo \(applicationDict) to complication")

    }


}

此外,在运行模拟器时,我会收到大量与以下内容类似的消息:
objc[7501]: Class SPAssetCacheAssets is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/System/Library/Frameworks/WatchKit.framework/WatchKit and /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/System/Library/PrivateFrameworks/SockPuppetGizmo.framework/SockPuppetGizmo. One of the two will be used. Which one is undefined.
objc[7501]: Class SPAssetCacheSyncData is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/System/Library/Frameworks/WatchKit.framework/WatchKit and /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/System/Library/PrivateFrameworks/SockPuppetGizmo.framework/SockPuppetGizmo. One of the two will be used. Which one is undefined.

最佳答案

使用 CLKComplicationServer像这样:

CLKComplicationServer* server = [CLKComplicationServer sharedInstance];
[server.activeComplications enumerateObjectsUsingBlock:^(CLKComplication * _Nonnull each, NSUInteger idx, BOOL * _Nonnull stop) {
    [server reloadTimelineForComplication: each];
}];

它将调用您的 ComplicationController .

关于apple-watch - 使用 IOS 数据更新 WatchOS2 ClockKit 并发症,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063515/

相关文章:

ios - 调用 ExtensionDelegate 为 Complication 创建/刷新数据

watchkit - 对于 Watch Complication 和 Time Travel,getTimelineEntriesForComplication 被(太)经常调用

ios - 以编程方式触发呼吸应用程序或 HRV 测量 [Apple Watch 4]

ios - 从 iPhone 应用程序回复观看消息

ios - 我可以在 WatchOS 2 模拟器上测试本地通知吗?

apple-watch - 有没有办法直接从 iPhone 应用程序更新复杂功能?

swift - 如何在模块化大复杂功能中设置带有文本的图像?

ios - 找不到要实例化的接口(interface) Controller 类 'InterfaceController'

ios - 使用 HKWorkoutSession 时如何避免将 watch 应用程序放在前面?

ios - 如何从 swift 2.2 中的观看按钮在手机 AV Controller 上启动电影?