【问题标题】:Copying plist to App Group Container - iOS 8将 plist 复制到应用程序组容器 - iOS 8
【发布时间】:2015-06-08 21:54:12
【问题描述】:

我正在向我的应用添加一个应用组,以便在应用和手表之间共享一个 plist。当应用程序首次启动时,我曾经将一个 plist 从包复制到 Documents。但是对于手表,我现在正试图将其转换为保存到容器中,但它似乎总是空的。目标启用了应用程序组,我在代码中使用了正确的名称。可能出了什么问题?

老路

// COPY PLIST TO DOCUMENTS
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];

NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"badger.com.vacations.plist"];

NSLog(@"plist path %@",destinationPath);
if (![fileManger fileExistsAtPath:destinationPath]){
    NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"badger.com.vacations.plist"];

    [fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}

新方法 - 不起作用

// COPY PLIST TO CONTAINER
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.xxxxx.xxx.container"];
    containerURL = [containerURL URLByAppendingPathComponent:@"name.com.data.plist"];
    NSString *destinationPath= containerURL.path;

    NSLog(@"destinationPath %@", containerURL);

    NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"name.com.data.plist"];
    [fileManger copyItemAtPath:sourcePath toPath:containerURL.path error:&error];

【问题讨论】:

  • stk 的回答很好,但我看不出有什么理由不能直接使用 plist 文件。到底发生了什么?没有写入文件?写入一个空文件? error 中有什么内容吗?

标签: plist nsfilemanager watchkit apple-watch ios-app-group


【解决方案1】:

您不能将 plist 共享为文件(或者我根本不知道此功能),而是生成一个新的 NSUserDefaults 实例,该实例可在目标之间共享。

看看这里: https://devforums.apple.com/message/977151#977151

或 Apple 文档

https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html

  • 在 Apple 会员中心的“标识符 > 应用组”下注册一个新的应用组(例如 group.de.myApp.sharedGroup)
  • 在 Apple 会员中心的“标识符 > 应用程序 ID”下,为需要共享以使用应用程序组功能的目标刷新您的应用程序 ID
  • 重新生成所有需要的 Provisioning Profiles 并将它们导入 Xcode
  • 返回 Xcode:在每个需要共享数据的目标中的“功能”下,将“应用组”设置为开启并添加之前注册的应用组。
  • 像这样与可共享的 NSUserDefaults 容器对话:

存储东西:

NSUserDefaults *groupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.de.myApp.sharedGroup"];
[groupDefaults setInteger:1337 forKey:@"testEntry"];
[groupDefaults synchronize];

阅读资料:

NSUserDefaults *groupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.de.myApp.sharedGroup"];
NSInteger testEntry = [groupDefaults integerForKey:@"testEntry"];
NSLog(@"testEntry: %ld", (long)testEntry);

【讨论】:

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