簡體   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