Search code examples
iosobjective-capple-watch

How can the Apple Watch Extension access a file in the NSDocumentDirectory?


I'm trying to access a plist file containing an array that is in the NSDocumentDirectory. This is the same directory where you have the ability to access files via File Sharing in iTunes. I tried to access the file using this code

- (instancetype)init {
    self = [super init];
    if (self){
         paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fav.out"];
        NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
        if (!arrayFromFile)
             arrayFromFile = [[NSArray alloc] init];
        self.favArray = [[NSMutableArray alloc] initWithArray:arrayFromFile];
    }
}

Solution

  • You can't directly use main app's files. You should set up an App Group and use path like this:

    NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.myApp"];