在我的项目中,我使用Watch Connectivity向监视和iPhone发送消息。在启动应用程序时,我可以向手机发送消息并接收字符串数组,但是当使用操作时,我会收到以下错误;
“错误Domain=WCErrorDomain Code=7012”消息回复时间太长。
事情是这样安排的;
首先,手表向电话发送一条消息,然后电话发送一个字符串数组,以在WKInterfaceTable中显示。这有时会在加载应用程序时起作用。(我获取所有名为NSManagedObjects的Items,并使用它们的title字符串属性存储在名为watchItems的array中。
但是,我在手表上有一个操作来删除数组中的所有项,并使用新的数据刷新表。
手表上的操作使用sendMessage函数将item发送到电话以从数组中删除,然后电话将更新后的数组发送给手表,手表更新表。但是,我要么得到相同的数组返回,要么出错。
非常简单,所以在Swift 3和Watch iOS 3/iOS 10之前,一切都很好;整个应用程序过去都正常工作。
我把一切都安排在这里;
手机应用程序代理
import WatchConnectivity
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {
var session : WCSession!
var items = [Items]()
func loadData() {
let moc = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest<Items>(entityName: "Items")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
request.predicate = NSPredicate(format: "remove == 0", "remove")
do {
try
self.items = moc!.fetch(request)
// success ...
} catch {
// failure
print("Fetch failed")
}
}
//WATCH EXTENSION FUNCTIONS
//IOS 9.3
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
//HAVE TO INCLUDE
@available(iOS 9.3, *)
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){
print("iPhone WCSession activation did complete")
}
@available(iOS 9.3, *)
func sessionDidDeactivate(_ session: WCSession) {}
func sessionWatchStateDidChange(_ session: WCSession) {}
func sessionDidBecomeInactive(_ session: WCSession) {
}
//APP DELEGATE FUNCTIONS
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
//Check if session is supported and Activate
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self;
session.activate()
}
return true
}
}
//DID RECIEVE MESSAGE
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Swift.Void) {
loadData()
func loadItems() {
watchItems.removeAll()
for a in self.items {
watchItems.append(a.title)
}
}
var watchItems = ["1","2","3","4","5"]
let value = message["Value"] as? String
//This is called when user loads app, and takes some time when using refresh action, sometimes times out
if value == "HELLOiPhone/+@=" {
print("Hello Message Recieved")
loadItems()
//send a reply
replyHandler( [ "Items" : Items ] )
}
//Not sure if receiving but does not delete array and send back to watch
if value == "removeALL@+=-/" {
for index in self.items {
index.remove = 1
//Saves MOC
}
loadData()
loadTasksData()
//send a reply
replyHandler( [ "Items" : Items ] )
}
else {
for index in self.items {
if index.title == value {
index.remove = 1
//Saves MOC
}
}
loadData()
loadTasksData()
//send a reply
replyHandler( [ "Items" : Items ] )
}
}WATCH
import WatchConnectivity
class SimplelistInterfaceController: WKInterfaceController, WCSessionDelegate {
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
@available(watchOS 2.2, *)
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
//Fetch data is a function which sends a "HELLOiPhone/+@=" message to receive the array and displays in the table. This works
fetchData()
}
var session : WCSession!
var items = ["Refresh Items"]
override func didAppear() {
fetchData()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
//Check if session is supported and Activate
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self
session.activate()
}
fetchData()
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
fetchData()
}
@IBAction func refresh() {
print("Refresh")
//Works but sometimes message is delayed
fetchData()
}
@IBAction func removeAll() {
print("Remove All Items is called")
if WCSession.default().isReachable {
let messageToSend = ["Value":"removeALL@+=-/"]
print("\(messageToSend)")
session.sendMessage(messageToSend, replyHandler: { replyMessage in
if let value = replyMessage["Items"] {
self.items = value as! [String]
Not receiving message
print("Did Recieve Message, items = \(self.items)")
}
}, errorHandler: {error in
// catch any errors here
print(error)
})
}
fetchData()
}
}发布于 2018-04-01 17:11:52
现在,您可以轻松地向您的iOS应用程序发送一条消息,以唤醒并从那里获取数据(例如从CoreData),使用任何WKInterfaceController中的上述函数,而完成块将拥有所需的数据,如
let dict: [String: Any] = ["request": "FirstLoad"]
WatchSessionManager.sharedManager.tryWatchSendMessage(message: dict,completion:{ (data) in print(data)})同样,您应该在WatchSessionManager端使用此iOS并接收请求,并且根据请求的键,您应该从核心存储/db获取数据,并在replyHandler of didreceiveMessage函数中以简单的键值字典模式发送自定义对象列表,如下所示。
func session(_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @escaping ([String: Any]) -> Void) {
var dict: [String: Any] = [String: Any]()
replyHandler(dict) //This dict will contain your resultant array to be sent to watchApp.
}有些时候,iOS应用程序(死状态)无法到达WatchApp,为了解决这个问题,您应该在大约3秒间隔的计时器内调用"tryWatchSendMessage“。当您从watchApp获得连接时,您应该使计时器失效。
sendMessage的WatchConnectivity功能非常强大,可以唤醒应用程序。您应该以优化的方式使用它。
发布于 2016-10-12 16:43:34
我刚刚处理了我的WatchOS应用程序。有一种情况是,我收到“回覆太久了”。
然后,我将后台任务处理程序添加到我的iOS应用程序中,并开始每秒钟向WatchOS应用程序发送消息。该消息包含UIApplication.shared.backgroundTimeRemaining。我得到:45秒44秒.6秒5秒.如果计时器运行在5秒以下,没有消息将传递到/从iOS应用程序,我们将得到“消息答复太长时间”。最简单的解决方案是,每次计时器低于15秒时,从手表发送到另一个电话。backgroundTimeRemaining将再次更新为45秒: 45,44,43,.,17,16,15,(空白消息),45,44,43,.
希望它能帮到别人
https://stackoverflow.com/questions/39515619
复制相似问题