【问题标题】:How to Set Permission for folders/files in iOS如何在 iOS 中设置文件夹/文件的权限
【发布时间】:2015-03-30 03:30:51
【问题描述】:

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

在文档文件夹中创建文件时是否可以设置只读权限?

或者任何替代解决方案?

【问题讨论】:

    标签: ios permissions directory


    【解决方案1】:

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

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

    【讨论】:

    • 不需要获取已有的属性,合并新的属性吗?
    • @David 如果文件具有其他特定属性,那么是的,那将是一个好主意。
    • 谢谢各位,我会尽力让你们知道我的发现。
    • 大卫,如何将新权限添加到该文件的现有权限中?请贴出代码sn-p。
    • @iOSEnthusiast 我更新了我的答案,提供了有关保留现有权限的详细信息。
    猜你喜欢
    • 2012-03-02
    • 2014-09-28
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2015-10-18
    • 2013-12-22
    • 2016-11-17
    • 2023-03-28
    相关资源
    最近更新 更多