如何与Watch OS共享数据以在使用CoreData时显示在WKInterfaceTable中 [英] How To Share Data with Watch OS 2 to display in WKInterfaceTable when working with CoreData

查看:330
本文介绍了如何与Watch OS共享数据以在使用CoreData时显示在WKInterfaceTable中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 WatchConnectivity 尝试发送 NSManagedObject 类型的数据 arrayOfOjects 到手表。每个对象有一个字符串属性 title



Watch上的 InterfaceController 加载并显示和空表 - 因为数组为空,所以当用户请求数据时,使用 didReceiveMessage 方法。



我不确定如何将字典数组添加到objectsArray以显示在 WKInterfaceTable 中。



有没有人知道我如何将数据发送到手表,在表格中显示,以进行更改并将其与手机同步?



Apple Watch:

  ObjectsInterfaceController:WKInterfaceController,WCSessionDelegate {

var session:WCSession!
var objectsArray = [[AnyObject]]()

@IBOutlet var table:WKInterfaceTable!
@IBOutlet var titleLabel:WKInterfaceLabel!

func loadTableData(){

table.setNumberOfRows(self.objectsArray.count,withRowType:CellRow)
if self.objectsArray.count> 0 {
for(index,name)in self.objectsArray.enumerate(){
let row = self.table.rowControllerAtIndex(index)as! CellRowController
row.objectCellLabel.setText(name.title)
}
}
}

override init(){
super.init ()
loadTableData()
}

override func awakeWithContext(context:AnyObject?){
super.awakeWithContext(context)
//接口对象
}

override func willActivate(){
//当观察控制器即将对用户可见时调用此方法
super.willActivate()
//检查是否支持会话并激活
if(WCSession.isSupported()){
session = WCSession.defaultSession()
session.delegate = self
session .activateSession()
}
}

// Swift
func session(session:WCSession,didReceiveMessage message:[String:AnyObject],replyHandler: :AnyObject]) - > Void){

let value = message [Value]

dispatch_async(dispatch_get_main_queue()){
self.objectsArray。 removeAll()
self.objectsArray.append(value!如!数组)
self.loadTableData()
}

//发送回复
replyHandler([Value:Yes])
b $ b}
}

iPhone

我已经获取所有对象并存储在数组中。

  var objectsArray = [Objects]()

func session(session:WCSession,didReceiveMessage message: [String:AnyObject],replyHandler:([String:AnyObject]) - > Void){

//发送回复
replyHandler([Value:[objectsArray]])

}

我需要能够修改对象的属性并保存在iPhone上的更改,但atm我甚至不能发送数据和显示在表:(我已经能够发送简单字符串值在设备之间的字典,而不是数组或实际数据。

解决方案

TL / DR:



(例如字符串,整数,双精度)。此问题有关发送自定义对象的详细信息



另一个问题:



即使您已归档或序列化托管对象,

A NSManagedObject 仅在自己的上下文中有效。在这种情况下,管理对象使用您的iOS应用程序上的特定 NSMangedObjectContext 注册。除了其上下文之外,托管对象不是有用的,并且其托管对象上下文不在手机的任何其他地方。


NSManagedObject实例不打算在队列之间传递。这样做可能会导致数据损坏和应用程序终止。当需要将一个管理对象引用从一个队列移交到另一个队列时,必须通过NSManagedObjectID实例来完成。


不可能将受管对象从一个上下文(或线程或队列)传递到同一个平台上的另一个上,则绝对不能在手机及其配对手表之间传递受管对象。



您可以做什么?




  • 有一种方法可以在手机和手表之间共享您的Core Data存储,您可以将托管对象ID转换为字符串(使用 URIRepresentation ),然后将这些字符串传递到手表,然后将这些字符串转换回对象ID并获取相应的对象。 此问题中有详细说明



    但是,


  • 一个更轻松的解决方案是,在watchOS 2上不再支持应用程序组,并保持两个不同的商店同步。传递有关标题的详细信息,跟踪您在手表上所做的任何更改,然后发送插入,删除或以其他方式更改的标题字典。





    这类似于 NSFetchedResultsControllerDelegate 如何响应更改以保持其结果同步。





有谁知道我如何发送数据到手表在表中显示以进行更改并将其与手机同步?


我给了您一个概述。任何更详细的东西将太广泛,无法涵盖在这个答案。我可以建议的是,开发人员使用第三方框架,或者写自己的实现。



一些注意事项:

请注意,您不想来回传输大量数据,从而降低用户的观看体验。保持您的手表应用程序的轻量级和响应性,因为它的理想设置只能使用几秒钟。



如果你可以简化你的手表应用程序设计(例如,只将待办事项列表项标记为已完成),您可以消除大量的同步开销,并将更复杂的任务委派给iOS应用程序。


I am using WatchConnectivity to try to send data of type NSManagedObject called arrayOfOjects to the Watch. Each object has a string property called title.

The InterfaceController on the Watch loads and displays and empty table - as intended because the array is empty, then when the user requests the data it is sent using the didReceiveMessage method on the phone.

I am unsure how to add the dictionary array to the objectsArray to display in the WKInterfaceTable.

Does anyone know how I can send the data to the watch to display in the table to make changes and sync them back with the phone ?

Apple Watch:

class ObjectsInterfaceController: WKInterfaceController, WCSessionDelegate {

var session : WCSession!
var objectsArray = [[AnyObject]]()

@IBOutlet var table: WKInterfaceTable!
@IBOutlet var titleLabel: WKInterfaceLabel!

func loadTableData() {

    table.setNumberOfRows(self.objectsArray.count, withRowType: "CellRow")
    if self.objectsArray.count > 0 {
        for (index, name) in self.objectsArray.enumerate() {
            let row = self.table.rowControllerAtIndex(index) as! CellRowController
            row.objectCellLabel.setText(name.title)
        }
    }
}

override init() {
    super.init()
    loadTableData()
}

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)
    // Interface Objects
}

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.defaultSession()
        session.delegate = self
        session.activateSession()
    }
}

//Swift
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

    let value = message["Value"]

    dispatch_async(dispatch_get_main_queue()) {
        self.objectsArray.removeAll()
        self.objectsArray.append(value! as! Array)
        self.loadTableData()
    }

    //send a reply
    replyHandler(["Value":"Yes"])

}
}

iPhone

I already fetch all the objects and store in array.

var objectsArray = [Objects]()

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

    //send a reply
    replyHandler(["Value": [objectsArray]])

}

I need to be able to modify the properties of the objects and save the changes on the iPhone but atm I cannot even send the data and display in the table :( I have been able to send simple string values within a dictionary between devices but not arrays or actual data.

解决方案

TL/DR:

You can only send basic types (such as strings, integers, doubles) to your watch. This question has more details about sending custom objects.

The other issue:

Even if you archived or serialized the managed objects, it's still not possible to send that particular data from the phone to the watch.

A NSManagedObject is only valid within its own context. In this case, the managed object are registered with a specific NSMangedObjectContext on your iOS app. The managed object is not useful apart from its context, and its managed object context doesn't exist anywhere else but the phone.

NSManagedObject instances are not intended to be passed between queues. Doing so can result in corruption of the data and termination of the application. When it is necessary to hand off a managed object reference from one queue to another, it must be done through NSManagedObjectID instances.

Since it's not possible pass a managed object from one context (or thread or queue) to another on the same platform, you definitely can't pass a managed object between the phone and its paired watch.

What can you do?

  • If you had a way to share your Core Data store between the phone and the watch, you could convert the managed object IDs to strings (using URIRepresentation), then pass those strings to the watch, then convert those strings back to object IDs and fetch the corresponding objects. This is explained in detail in this question.

    However, app groups are no longer supported on watchOS 2, and it would be very complex to keep two different stores in sync across devices.

  • A much lighter solution is to pass details about the title, keep track of whatever changes you make on the watch, then send back a dictionary of titles that were inserted, deleted, or otherwise changed.

    The phone would then update the managed objects corresponding to those changed titles.

    This is similar to how NSFetchedResultsControllerDelegate responds to changes to keep its results in sync.

Does anyone know how I can send the data to the watch to display in the table to make changes and sync them back with the phone?

I gave you a general overview. Anything more detailed would be far too broad to cover in this answer. All I can suggest is that developers either used a third-party framework, or wrote their own implementation.

Some considerations:

Just keep in mind that you don't want to degrade the user's watch experience by transferring large amounts of data back and forth. Keep your watch app lightweight and responsive, as it's ideally only designed to be used for a few seconds.

If you can simplify your watch app design (e.g., only marking a todo list item as completed), you can eliminate much of the "sync" overhead, and delegate the more complex tasks to the iOS app.

这篇关于如何与Watch OS共享数据以在使用CoreData时显示在WKInterfaceTable中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆