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

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

我在 Objective-C 中有一个 Xcode tvOS 项目。 我正在尝试使用以下代码将示例 fileName.txt 文件保存到 Documents 文件夹中:

#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

但是当我 运行 应用程序时出现此错误:错误:您无权在“文档”文件夹中保存文件“fileName.txt” .

在 iOS 中它起作用了。

您无权访问 tvOS 上的文档。

这里来自苹果(详见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.