【问题标题】:Synchronizing Apple Watch and iPhone using Swift 3 and Realm使用 Swift 3 和 Realm 同步 Apple Watch 和 iPhone
【发布时间】:2017-06-07 16:48:57
【问题描述】:

我需要在 Apple Watch 和 iPhone 上显示和修改我的数据结构。

数据库:

我目前正在使用一个简单的领域结构,其中我有一个对象 A 和一个可以容纳很多 A 的对象 B。

因此,在 iPhone 上,用户可以创建 B 并添加 A,当然还可以查看所有 A 和 B。

我希望 Apple watch 显示当前 B 的所有 A,并让用户有机会将新 A 添加到当前 B。

我尝试过的方式:

我想将洞 Realm 文件从 iPhone 移动到手表或其他方式。 (这是网上的提示)

iPhone 代码:

    override func viewDidLoad() {
    super.viewDidLoad()


    if WCSession.isSupported() { //makes sure it's not an iPad or iPod
        let watchSession = WCSession.default()
        watchSession.delegate = self
        watchSession.activate()

        transferRealmFile()

        if  watchSession.isWatchAppInstalled {
            do {
                try watchSession.updateApplicationContext(["foo": "bar"])
            } catch let error as NSError {
                print(error.description)
            }
        }
    }
}
func transferRealmFile(){
    if let path = Realm.Configuration().fileURL {
        WCSession.default().transferFile(path, metadata: nil)
    }
}

WathcKit 扩展:

  func session(_ session: WCSession, didReceive file: WCSessionFile) {

    //set the recieved file to default Realm file
    var config = Realm.Configuration()
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    let realmURL = documentsDirectory.appendingPathComponent("data.realm")
    if FileManager.default.fileExists(atPath: realmURL.path){
        try! FileManager.default.removeItem(at: realmURL)
    }
    try! FileManager.default.copyItem(at: file.fileURL, to: realmURL)
    config.fileURL = realmURL
    Realm.Configuration.defaultConfiguration = config
}

然后我每次写入 Realm 时都会调用 transferRealmFile()。这可行,但我无法解决这个问题:

问题:

  1. 只启动watchKit App是不行的。
  2. Apple Watch 到 iPhone 的工作方式不同。 (我想我需要更改 didRecived 代码,但我不知道是什么)

问题:

您知道谁来解决这 2 个问题,或者您是否知道更好的方法来处理这种情况,或者我们在 iPhone 和 Watch 之间的交互方式会在 WathcOS 3 中改变吗?

【问题讨论】:

    标签: ios swift swift3 realm watchkit


    【解决方案1】:

    使用 watchOS1,可以使用 AppGroups 在 iOS 应用程序及其 Watch 扩展程序之间共享资源(甚至是您的 Realm 数据库)。但是,Apple 在 watchOS 2 中删除了此功能,因此现在在 iOS 和 watchOS 应用程序之间共享数据的唯一方法是通过WatchConnectivity。看看this的答案。

    遗憾的是,WatchConnectivity 框架要求 WCSession 在两个设备上都处于活动状态以传输数据,因此您无法真正解决问题 1。

    在我看来,仅在两个应用程序之间传达更改而不发送整个 Realm 文件是一个更好的解决方案,因为您的 Realm 文件可能会变得非常大,因此向前和向后发送它可能会花费大量时间并且资源,而仅发送更改应该更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多