如何在iOS中设置文件夹/文件的权限

如何设置iOS内部文档文件夹中的文件夹和文件的权限?

在文档文件夹中创建文件时是否可以设置只读权限?

或任何替代解决方案?

根据您创建文件的方式,您可以指定文件属性。 要使文件为只读,请传递以下属性:

NSDictionary *attributes = @{ NSFilePosixPermissions : @(0444) }; 

注意值中的前导0 。 这很重要。 它表示这是一个八进制数。

另一个选项是在创建文件后设置文件的属性:

 NSString *path = ... // the path to the file NSFileManager *fm = [NSFileManager defaultManager]; NSError *error = nil; if (![fm setAttributes:attributes ofItemAtPath:path error:&error]) { NSLog(@"Unable to make %@ read-only: %@", path, error); } 

更新:

要确保保留现有权限,请执行以下操作:

 NSString *path = ... // the path to the file NSFileManager *fm = [NSFileManager defaultManager]; NSError *error = nil; // Get the current permissions NSDictionary *currentPerms = [fm attributesOfFileSystemForPath:path error:&error]; if (currentPerms) { // Update the permissions with the new permission NSMutableDictionary *attributes = [currentPerms mutableCopy]; attributes[NSFilePosixPermissions] = @(0444); if (![fm setAttributes:attributes ofItemAtPath:path error:&error]) { NSLog(@"Unable to make %@ read-only: %@", path, error); } } else { NSLog(@"Unable to read permissions for %@: %@", path, error); }