ios - WatchKit 并发症 : get Complication data from extension delegate

标签 ios xcode swift watchkit watchos-2

我的 WatchKit 扩展中有我需要的所有数据(从 iOS 应用程序传递)。

我使用 WatchKit InterfaceController 中的数据填充了一个表格,效果很好。

我正在尝试找出最佳方法来在我的 WatchKit ComplicationController 中获取相同的数据。

目前,在 InterfaceController 中,使用 didReceiveUserInfo 传入数据:

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

    if let beachValue = userInfo["Surf"] as? String {

        places.append(Place(dataDictionary: ["Surf" : surfValue]))

    } else {
        print("Something went wrong")
    }

}

我是否需要在我的 ComplicationController 中调用相同的 WCSession 方法并再次获取整个数据,或者是否有任何更简单的方法我访问相同的数据以在 ComplicationController 中使用?

感谢任何帮助。谢谢!

编辑:

我的表函数:

func makeTable() {

    // Per SO
    let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
    let accessVar = myDelegate.places
    self.rowTable.setNumberOfRows(accessVar.count, withRowType: "rows")

    for (index, evt) in accessVar.enumerate() {

        if let row = rowTable.rowControllerAtIndex(index) as? TableRowController {

            row.mLabel.setText(evt.evMat)

        } else {
            print(“No”)
        }
    }

}

最佳答案

// Get the complication data from the extension delegate.
let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
var data : Dictionary = myDelegate.myComplicationData[ComplicationCurrentEntry]!

以上来自Apple's Doc只是在扩展委托(delegate)中存储复杂功能所需的数据的示例,以了解如何作为单例轻松访问它。对“myComplicationData”的引用是 Dictionary 的示例,默认情况下不是 ExtensionDelegate 中的参数。

要么将你自己的类设置为一个单例类,像这样为你的 watch 保存数据:

// Access by calling:
// Model.sharedModel.modelVal1
class Model {
    static let sharedModel = Model()
    var modelVal1: Float!
    var modelVal2: String!
}

或者使用扩展委托(delegate)作为你的单例并将你的属性添加到它的类中,如下所示。这将允许您访问您在 ExtensionDelegate 中创建的任何变量。

// ExtensionDelegate.swift
class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var dataVar1: Float!
    var dataVar2: String!
    var myDictionary: [String: String]!
}


// ComplicationController.swift
import WatchKit

class ComplicationController: NSObject, CLKComplicationDataSource {

    func someMethod() {
        let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
        // Here is an example of accessing the Float variable 
        let accessVar = myDelegate.dataVar1
        let myDict = myDelegate.myDictionary
    }
}

使用任何一种方式都有助于将您的数据保存在一个位置,这样您就可以随时从 watch 扩展中的任何类访问它。

关于ios - WatchKit 并发症 : get Complication data from extension delegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190685/

相关文章:

logging - xcode 6 beta 6 选项卡栏 + 导航 Controller 烦人的日志消息

iphone - 如何从 iPhone 的字符串中删除标签?

ios - UIImage 从 iOS 图像库中选择

ios - 未调用 UICollectionView 方法(collectionView cellForItemAt indexPath)

iphone - 只需更改 iPhone 应用程序的应用程序可执行文件的名称

iphone - 如何在标签中获取 map 注释标题样式/字体

ios - 在 iOS 上学习编码——swift 与 Objective C 的困境

ios - Phonegap (Cordova) iOS 按钮点击

ios - 使用 AVAudioEngine 为低延迟节拍器安排声音

ios - Swift:单击按钮时断言失败