Search code examples
objective-cxcodetvos

Xcode tvOS - Error: You don’t have permission to save the file “fileName.txt” in the folder “Documents”


I have an Xcode tvOS project in Objective-C. I'm trying to save a sample fileName.txt file into the Documents folder with this code:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self applicationDocumentsDirectory];

    NSString *path = [[self applicationDocumentsDirectory].relativePath
                           stringByAppendingPathComponent:@"fileName.txt"];
    NSString* sampleText = @"Prova";
    NSError* err;
    [sampleText writeToFile:path atomically:YES
                           encoding:NSUTF8StringEncoding error:&err];
    if(err != nil) {
        NSLog(@"Error: %@", [err localizedDescription]);
    }
}

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory {
    NSLog(@"%@", [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
    inDomains:NSUserDomainMask] lastObject]);
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
         inDomains:NSUserDomainMask] lastObject];
}


@end

But I get this error when I run the app: Error: You don’t have permission to save the file “fileName.txt” in the folder “Documents”.

In iOS it works instead.


Solution

  • You don't have access to Documents on tvOS.

    Here is from Apple (see for details here):

    Local Storage for Your App Is Limited

    • The maximum size for a tvOS app bundle 4 GB. Moreover, your app can only access 500 KB of persistent storage that is local to the device (using the NSUserDefaults class). Outside of this limited local storage, all other data must be purgeable by the operating system when space is low. You have a few options for managing these resources:
    • Your app can store and retrieve user data in iCloud. Your app can download the data it needs into its cache directory. Downloaded data is not deleted while the app is running. However, when space is low and your app is not running, this data may be deleted. Do not use the entire cache space as this can cause unpredictable results.
    • Your app can package read-only assets using on-demand resources. Then, at runtime, your app requests the resources it needs, and the operating system automatically downloads and manages those resources. Knowing how and when to load new assets while keeping your users engaged is critical to creating a successful app. For information on on-demand resources, see On-Demand Resources Guide. This means that every app developed for the new Apple TV must be able to store data in iCloud and retrieve it in a way that provides a great customer experience.