【发布时间】:2015-03-30 03:30:51
【问题描述】:
如何在 iOS 中为文档文件夹中的文件夹和文件设置权限?
在文档文件夹中创建文件时是否可以设置只读权限?
或者任何替代解决方案?
【问题讨论】:
标签: ios permissions directory
如何在 iOS 中为文档文件夹中的文件夹和文件设置权限?
在文档文件夹中创建文件时是否可以设置只读权限?
或者任何替代解决方案?
【问题讨论】:
标签: ios permissions directory
根据您创建文件的方式,您可以指定文件属性。要使文件只读,请传递以下属性:
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);
}
【讨论】: