NSFileManager & NSFilePosixPermissions

I want to use octal permissions (used for chmod) for NSFilePosixPermissions. Here is what I have done now:

NSFileManager *manager = [NSFileManager defaultManager]; NSDictionary *attributes; [attributes setValue:[NSString stringWithFormat:@"%d", 0777] forKey:@"NSFilePosixPermissions"]; // chmod permissions 777 [manager setAttributes:attributes ofItemAtPath:@"/Users/lucky/Desktop/script" error:nil]; 

I am not getting the error, but when I check the result with "ls -o", the resolution is not -rwxrwxrwx.

What's wrong? Thanks for the help.

+6
source share
3 answers

First, NSFilePosixPermissions is the name of a constant. Its value may also be the same, but this is not guaranteed. The value of the NSFilePosixPermissions constant can vary between platform releases, for example, from @"NSFilePosixPermissions" to @"posixPermisions" . That would break your code. The correct way is to use the constant as NSFilePosixPermissions , not @"NSFilePosixPermissions" .

In addition, the NSFilePosixPermissions link talks about NSFilePosixPermisions :

The corresponding value is an NSNumber object. Use the shortValue method to get an integer value for permissions.

The correct way to set POSIX permissions is:

 // chmod permissions 777 // Swift attributes[NSFilePosixPermissions] = 0o777 // Objective-C [attributes setValue:[NSNumber numberWithShort:0777] forKey:NSFilePosixPermissions]; 
+14
source

Solution in Swift 3

 let fm = FileManager.default var attributes = [FileAttributeKey : Any]() attributes[.posixPermissions] = 0o777 do { try fm.setAttributes(attributes, ofItemAtPath: path.path) }catch let error { print("Permissions error: ", error) } 
+2
source

Solution in Swift 4

I tried using 0o777 and this did not change the file to read. I believe the correct way to do this is:

 let fileManager = FileManager.default let documentsUrl: URL = self.fileManager.urls(for: .documentDirectory, in: .userDomainMask).first as URL! let destinationFileUrl = documentsUrl.appendingPathComponent(fileName) let readOnlyAttribute: [FileAttributeKey: Any] = [ .posixPermissions: 0777 ] do { try fileManager.setAttributes(readOnlyAttribute, ofItemAtPath: destinationFileUrl.path) if fileManager.isWritableFile(atPath: destinationFileUrl.path) { print("writeable") } else { print("read only") } } catch let error { print("Could not set attributes to file: \(error.localizedDescription)") } 
0
source

Source: https://habr.com/ru/post/910440/


All Articles