ios - WatchKit 应用程序在进入后台后丢失数据 - Swift

标签 ios swift watchkit apple-watch watchos-2

我使用 (watchOS 2) applicationContext 方法将字典从 iPhone 传递到 watch 。

iPhone 应用程序内部:

func giveMeInfo(){
    var lastStringUsed = porkee288.storyPoints.last!
    do {
        let resultDict = ["dict": myDict]
        try WCSession.defaultSession().updateApplicationContext(resultDict)
    }  
    catch {
        print("Something wrong happened")
    }
}

watch 应用内部:

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {

    dispatch_async(dispatch_get_main_queue()) { () -> Void in

        if let retrievedDict = applicationContext["dict"] as? [String : String] {

                self.dictInsideWatch = retrievedDict     
        }
    }
}

数据是由watchKit中的tableview很好地获取的,但是,每次应用程序进入后台时,数据都会自动丢失,这很奇怪,因为iPhone 应用程序词典具有一定的持久性(至少在被暂停之前)。

您建议采取什么措施来解决此问题并防止数据消失?

最佳答案

您描述的问题是,一旦您返回 watch 应用程序,表格就不会显示任何数据。尽管您没有显示该特定代码,但这可能是由于下次打开应用程序时字典为空。

由于应用程序上下文仅接收一次,因此您可能用于重新加载表的任何属性观察器或方法只会在数据新到达时触发,不会在应用程序恢复时触发。

当你的字典为空时,你可以依靠 receivedApplicationContext属性来访问表中最近收到的数据。

A dictionary containing the last update data received from a paired and active device. (read-only)

Use this method to access the most recently received update dictionary. The session object also sends a newly arrived dictionary to the session:didReceiveApplicationContext: method of its delegate.

您还可以将字典保留在 NSUserDefaults 中,以处理您的应用在挂起时终止的情况。

您没有展示获得数据后如何调用loadTable()。一旦您(收到新数据或)检索了持久数据,您肯定想这样做。

if !session.receivedApplicationContext.keys.isEmpty {
    // Use most recently received dictionary
    dictInsideWatch = receivedApplicationContext["dict"]
} else {
    // Use persisted dictionary
    dictInsideWatch = NSUserDefaults.standardUserDefaults().dictionaryForKey("dict") ?? [:]
}
loadTable()

如果您采用这种方法,请确保保留数据(在收到数据后立即保留数据,或者在应用程序即将进入非事件状态时保留数据)。

关于ios - WatchKit 应用程序在进入后台后丢失数据 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968149/

相关文章:

ios - 通过子类化 UILabel 以在 Storyboard 上使用的标准文本颜色 - (IBOutlet)

swift - 为覆盖便捷初始化的 SKScene 创建自定义初始化器?(文件名为 :)

ios - 如何获得星期一 00 :00 of current week? Swift 3

ios - 在 Apple Watch 中调用 URL 的最佳做法是什么?

ios - 为什么在打包适用于 iOS 的 Adob​​e AIR 应用程序 (.IPA) 时 FDT 显示 Java 堆错误

iphone - 获取响应映射对象的Json字符串 restkit v0.2.20

iphone - 从 iPhone 麦克风检测节拍

ios - 我的 UITapGestureRecognizer 不工作

ios - WatchKit 错误 - 没有通知负载

app-store-connect - 存档上的 WatchKit2 错误 - WatchKit 应用程序不包含任何 WatchKit 扩展