1

我有一个应用程序可以保存和使用 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];
4

2 回答 2

3

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

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

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

于 2015-04-23T15:41:19.427 回答
0

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

有两个步骤:

  1. 为您要使用的每个 plist 启用 WatchKit App Extension Target Membership。点击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
    }
    
于 2015-05-17T16:07:15.850 回答