How to Set Permission for folders/files in iOS

自闭症网瘾萝莉.ら 提交于 2019-12-12 16:20:19

问题


How can I set permission to folders and files in iOS which is there inside documents folder?

Is it possible to set read only permission while creating files inside documents folder?

Or any alternative solution ?


回答1:


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. 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);
}


来源:https://stackoverflow.com/questions/28239577/how-to-set-permission-for-folders-files-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!