Bhat
Bhat

Reputation: 602

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?

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

Or any alternative solution ?

Upvotes: 3

Views: 6296

Answers (1)

rmaddy
rmaddy

Reputation: 318804

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

Upvotes: 4

Related Questions