我希望我的複雜功能通過Watch Connectivity從iPhone獲取數據。我正在使用sendMessage
即時消息傳遞技術。結合WatchConnectivity和複雜功能
我不希望iPhone應用程序在我嘗試獲取數據時打開,因此需要在後臺工作。
在我的ViewController在我的iPhone:
import UIKit
import WatchConnectivity
class ViewController: UIViewController, WCSessionDelegate {
var session: WCSession!
override func viewDidLoad() {
super.viewDidLoad()
if WCSession.isSupported() {
self.session = WCSession.defaultSession()
self.session.delegate = self
self.session.activateSession()
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
if message.count != 1 { return }
if message["request"] != nil {
replyHandler(["response" : "data"])
}
}
在我ComplicationController
var session: WCSession!
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
if complication.family != .ModularSmall {
handler(nil)
}
if WCSession.isSupported() {
self.session = WCSession.defaultSession()
self.session.delegate = self
self.session.activateSession()
}
var respondedString = "not"
session.sendMessage(["request" : ""], replyHandler: {
(resp) -> Void in
respondedString = resp["response"]
}, errorHandler: nil)
let circularTemplate = CLKComplicationTemplateModularSmallSimpleText()
circularTemplate.textProvider = CLKSimpleTextProvider(text: respondedString)
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: circularTemplate)
handler(timelineEntry)
}
我可以在我的收藏唯一看到的是 「不」。爲什麼複雜功能不顯示接收到的數據?
另外,您可能想在AppDelegate中設置iOS會話,而不是視圖控制器。您總是希望儘快激活它(並使其在應用程序範圍內可用)。 – 2016-04-26 07:30:23