如何在iOS中设置文件夹/文件的权限 [英] How to Set Permission for folders/files in iOS

查看:2825
本文介绍了如何在iOS中设置文件夹/文件的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在documents文件夹内创建文件时可以设置只读权限吗?

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

或任何其他解决方案?

推荐答案

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

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

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

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

更新:

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

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

这篇关于如何在iOS中设置文件夹/文件的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆