WatchKit Complication: get Complication data from extension delegate

前端 未结 2 2129
南旧
南旧 2020-12-29 13:56

I have all the data I need in my WatchKit Extension (passed from the iOS app).

I used the data in the WatchKit InterfaceController to f

相关标签:
2条回答
  • 2020-12-29 14:21
    // Get the complication data from the extension delegate.
    let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
    var data : Dictionary = myDelegate.myComplicationData[ComplicationCurrentEntry]!
    

    Above from Apple's Doc is just an example on storing the data you need for your complication in your extension delegate seeing as how you can access it easily as a singleton. The reference to "myComplicationData" is an example of a Dictionary and is not a parameter in the ExtensionDelegate by default.

    Either set up your own class as a singleton which holds data for your watch like so:

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

    Or use the extension delegate as your singleton and add your properties to its class like below. This will allow you to access whatever variables you create in your 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
        }
    }
    

    Using either way will help keep your data in one spot so you can always access it from any class in your watch extension.

    0 讨论(0)
  • 2020-12-29 14:38

    Well, what I have done in my app is to set up another singelton class to be responsible for fetching and holding of data for both my Watch app and complication. But that doesnt look like the best way for me. Unfortunately I do not get the Apple code

    var data : Dictionary = myDelegate.myComplicationData[ComplicationCurrentEntry]!
    

    at all. I dont understand where this myComplicationData comes from.

    0 讨论(0)
提交回复
热议问题