【发布时间】:2016-04-26 06:02:49
【问题描述】:
我希望我的复杂功能通过 Watch Connectivity 从 iPhone 获取数据。我正在使用sendMessage Instant Messaging 技术。
我不希望我的 iPhone 应用在我尝试获取数据时打开,所以这需要在后台运行。
在我 iPhone 上的 ViewController 中:
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)
}
我在手表上唯一能看到的是“不是”。为什么complication不显示接收到的数据?
【问题讨论】:
-
顺便说一句,您可能希望在
AppDelegate中设置iOS 会话而不是视图控制器。您总是希望尽快激活它(并使其在应用范围内可用)。
标签: swift watchos-2 watchconnectivity apple-watch-complication wcsession