[英]How to Set Permission for folders/files in iOS
How can I set permission to folders and files in iOS which is there inside documents folder? 如何设置iOS内部文档文件夹中的文件夹和文件的权限?
Is it possible to set read only permission while creating files inside documents folder? 在文档文件夹中创建文件时是否可以设置只读权限?
Or any alternative solution ? 或任何替代解决方案?
Depending on how you create the file, you can specify file attributes. 根据您创建文件的方式,您可以指定文件属性。 To make a file read-only, pass the following attributes:
要使文件成为只读,请传递以下属性:
NSDictionary *attributes = @{ NSFilePosixPermissions : @(0444) };
Note the leading 0
in the value. 注意值中的前导
0
。 That's important. 这很重要。 It indicates that this is an octal number.
它表示这是一个八进制数。
Another option is to set the file's attributes after it has been created: 另一个选项是在创建文件后设置文件的属性:
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);
}
Update: 更新:
To ensure existing permissions are kept, do the following: 要确保保留现有权限,请执行以下操作:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.