在 iOS 应用程序和 WatchKit 扩展之间共享 Plist

Share Plist between iOS App and WatchKit Extension

我有一个应用程序可以保存和使用 plist 文件中的数据。我正在开发一个 WatchKit 扩展,它需要访问同一个 plist 文件来显示数据并保存到文件中。我知道我需要使用应用组,但我不知道如何在 iOS 应用和 WatchKit 扩展之间共享 plist。

这是我目前在 iOS 应用程序中保存到 plist 的方式。

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"locations.plist"];
    BOOL fileExists = [fileManager fileExistsAtPath:docPath];
    NSError *error = nil;

    if (!fileExists) {
        NSString *strSourcePath = [[NSBundle mainBundle]pathForResource:@"locations" ofType:@"plist"];
        [fileManager copyItemAtPath:strSourcePath toPath:docPath error:&error];
    }

    NSString *path = docPath;
    NSMutableArray *plistArray = [[NSMutableArray alloc]initWithContentsOfFile:path];
    NSDictionary *locationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.locationNameTextField.text, @"locationName", latString, @"latitude", longString, @"longitude", nil];
    [plistArray insertObject:locationDictionary atIndex:0];
    [plistArray writeToFile:docPath atomically:YES];

一旦您设置了您的应用程序组(在您的主要 iPhone 应用程序和 Watch Extension 中),您可以获得共享文件夹的路径:

NSURL *groupContainerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupSuiteName"];
NSString *groupContainerPath = [groupContainerURL path];

然后您可以使用 groupContainerPath 构建您的 docPath。否则,您的代码应该按原样工作。

我能够使用 Swift.

在我的 WatchKit 应用程序中成功地使用来自现有主要 iPhone 应用程序的 plist 数据

有两个步骤:

  1. 为您要使用的每个 plist 启用 WatchKit 应用程序扩展目标成员资格。点击plist,然后:

  1. 这是我用来读取 plist 的 Swift 代码,它有 "id" 和 "name" 字段。

    func valueFromPlist(value: Int, file: String) -> String? {
        if let plistpath = NSBundle.mainBundle().pathForResource(file as String, ofType: "plist") {
    
            if let entries = NSArray(contentsOfFile: plistpath) as Array? {
                var entry = Dictionary<String, Int>()
    
                for entry in entries {
                    if let id = entry.objectForKey("id") as? Int {
                        if id == value {
                            if let name = entry.objectForKey("name") as? String {
                                return name
                            }
                        }
                    }
                }
            }
        }
        return nil
    }