【问题标题】:Share Plist between iOS App and WatchKit Extension在 iOS App 和 WatchKit 扩展之间共享 Plist
【发布时间】:2015-04-23 14:39:57
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c watchkit ios-app-group


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我能够使用 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
        }
        

      【讨论】:

        猜你喜欢
        • 2019-03-12
        • 1970-01-01
        • 2018-07-12
        • 1970-01-01
        • 2018-01-18
        • 2014-08-29
        • 1970-01-01
        • 2019-03-29
        相关资源
        最近更新 更多