简体   繁体   English

应用程序组中的NSUserDefaults无效

[英]NSUserDefaults in App Groups Not Working

I am trying to use the App Groups Entitlement in my app for NSUserDefaults handling data between the iPhone app and the WatchKit Extension. 我正在尝试在我的应用程序中使用App Groups Entitlement来处理iPhone应用程序和WatchKit扩展之间的NSUserDefaults数据。

I went to Capabilities in the iPhone target, and turned on App Groups, and made sure that group.com.316apps.iPrayed was selected. 我在iPhone目标中访问了Capabilities,并启用了App Groups,并确保选择了group.com.316apps.iPrayed。 I then went to the WatchKit Extension Target and did the same for its Capabilities. 然后我去了WatchKit扩展目标并为其功能做了同样的事情。

On the iPhone side of the app I put in the following code: 在应用程序的iPhone端,我输入以下代码:

PFUser *me2 = [PFUser currentUser];
        NSLog(@"USERNAME%@", me2.username);
                NSUserDefaults *testDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.316apps.iPrayed"];
        [testDefaults setObject:me2.username forKey:@"username"];
        [testDefaults setObject:me2.password forKey:@"password"];

        [testDefaults synchronize];

In the WatchKit InterfaceController, I have the following, but the NSLog always shows 'null' 在WatchKit InterfaceController中,我有以下内容,但NSLog始终显示'null'

NSUserDefaults *testDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.316apps.iPrayed"];
    NSString *theirUser = [testDefaults objectForKey:@"username"];
    NSString *theirPass = [testDefaults objectForKey:@"password"];
    NSLog(@"%@", theirUser);

Why is the WatchKit not reading the NSUserDefaults properly? 为什么WatchKit没有正确读取NSUserDefaults?

NOTE My bundle identifier is different for the watch kit extension target. 注意我的捆绑包标识符对于监视工具包扩展目标是不同的。 Do I need a new Apple ID for that? 我需要一个新的Apple ID吗?

It is OK your bundle identifiers are not the same, however they should be in this format 您的捆绑标识符不一样,但它们应该采用这种格式

The App Bundle ID -> com.companyName.productName
The Extension Bundle ID -> com.companyName.productName.extensionName

If they follow the formats above then refer to the answer below 如果他们遵循上述格式,请参阅下面的答案

You need to add an observer that knows when a value in NSUserDefaults has changed. 您需要添加一个知道NSUserDefaults的值NSUserDefaults发生更改的观察者。

Refer to this code: 请参阅此代码:

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userDefaultsDidChange:)
                                                 name:NSUserDefaultsDidChangeNotification
                                               object:nil];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM