在Extension Delegate

时间:2016-02-19 00:47:47

标签: ios xcode swift watchkit watch-os-2

我正在使用ExtensionDelegate,因此我可以从我的evnts(最终InterfaceController)访问ComplicationController变量。

当我从evnts 获取数据时,需要在ExtensionDelegate中刷新WCSession, didReceiveUserInfo,但无法弄清楚如何,任何想法?

原因是:evnts为空,因为它会在WCSession, didReceiveUserInfo运行之前被调用以实际获取数据。

(有任何问题只是让我知道,并会根据需要发布任何额外的代码!)

ExtensionDelegate

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var evnts = [Evnt]()
}

InterfaceController

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

    if let tColorValue = userInfo["TeamColor"] as? String, let matchValue = userInfo["Matchup"] as? String {

        let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
        var extEvnts = myDelegate.evnts

        receivedData.append(["TeamColor" : tColorValue , "Matchup" : matchValue])
        extEvnts.append(Evnt(dataDictionary: ["TeamColor" : tColorValue , "Matchup" : matchValue]))

        doTable()

    } else {
        print("tColorValue and matchValue are not same as dictionary value")
    }

}


func doTable() {

    let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
    let extEvnts = myDelegate.evnts

    self.rowTable.setNumberOfRows(extEvnts.count, withRowType: "rows")

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

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

            row.mLabel.setText(evt.eventMatch)
            row.cGroup.setBackgroundColor(colorWithHexString(evt.eventTColor)) 
        } else {
            print("nope")
        }
    }    
}

1 个答案:

答案 0 :(得分:1)

您可以让evnts中的ExtensionDelegate成为静态变量

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    static var evnts = [Evnt]()
}

然后你还需要做出改变:

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

    if let tColorValue = userInfo["TeamColor"] as? String, let matchValue = userInfo["Matchup"] as? String {

        receivedData.append(["TeamColor" : tColorValue , "Matchup" : matchValue])
        ExtensionDelegate.evnts.append(Evnt(dataDictionary: ["TeamColor" : tColorValue , "Matchup" : matchValue]))

        doTable()

    } else {
        print("tColorValue and matchValue are not same as dictionary value")
    }

}

func doTable() {

    let extEvnts = ExtensionDelegate.evnts

    self.rowTable.setNumberOfRows(extEvnts.count, withRowType: "rows")

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

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

            row.mLabel.setText(evt.eventMatch)
            row.cGroup.setBackgroundColor(colorWithHexString(evt.eventTColor)) 
        } else {
            print("nope")
        }
    }    
}