iOS 9和WatchOS 2上的NSUserDefaults(suiteName :) - 无法正常工作? [英] NSUserDefaults(suiteName:) on iOS 9 and WatchOS 2 - not working?

查看:140
本文介绍了iOS 9和WatchOS 2上的NSUserDefaults(suiteName :) - 无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前做过这个,但似乎没有任何效果。这是我的代码:

I've done this before but nothing seems to be working. Here's my code:

在iOS应用中保存

let groupDefaults = NSUserDefaults(suiteName: "group.company.appSharedDefaults")
groupDefaults?.setObject(theArray, forKey: "theKey")
groupDefaults?.synchronize()

阅读(适用于iOS但不适用于WatchOS 2)

let groupDefaults = NSUserDefaults(suiteName: "group.company.appSharedDefaults")

if groupDefaults!.objectForKey("theKey") != nil {
    textEmojiArray = NSMutableArray(array: groupDefaults!.objectForKey("theKey") as! NSArray)
} else {        
    //error
}

两个.entitlements文件都包含 group.company.appSharedDefaults

Both .entitlements files contain group.company.appSharedDefaults

已启用应用程序组功能,并在两个目标上都检查了相应的组。

App Groups capability have been turned on and appropriate group checked off on both targets.

现在,当我在watch objectForKey上运行读取代码时返回零,但它iOS上的orks(设备和模拟器结果相同)。

Right now when I run the read code on the watch objectForKey returns nil but it works on iOS (device and simulator results are the same).

我缺少什么!?

推荐答案

在watchOS 2中,您需要记住有2个不同的进程在运行:

In watchOS 2 you need to keep in mind that there is 2 different processes running:


  1. Apple Watch流程

  2. iPhone流程

这两个流程都有自己的沙箱,这就是为什么他们称之为沙箱native,所以如果你尝试使用共享的NSUserDefaults它将无法工作,因为Apple Watch应用程序的沙箱与主机iPhone应用程序完全不同。

Both of these processes have their own sandbox that's why they call it "native", so if you try to use the shared NSUserDefaults it will not work because the Apple watch app has a completely different sandbox than the host iPhone app.

如果您想将手机中的东西保存到Apple手表上的NSUserDefaults目标:

使用 WatchConnectivity 将您要保存的数据发送到手表。
然后当手表收到您发送给它的数据时,将其保存到Apple手表的默认NSUserDefaults。

Use WatchConnectivity to send the data you want to save to the watch. Then when the watch receives the data you sent to it, save it to the Apple watch's default NSUserDefaults.

这篇关于iOS 9和WatchOS 2上的NSUserDefaults(suiteName :) - 无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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