繁体   English   中英

在iOS App和WatchKit Extension之间共享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 App扩展目标成员资格。 点击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 } 

暂无
暂无

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

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