iOS 9 read file permission

前端 未结 4 1111
谎友^
谎友^ 2020-12-20 15:16

In iOS 9+ I get a nil on any attempt to read from file. The file in this case is a image file path.
using

NSData(contentsOfFile: stringpath, options: NSD         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 16:10

    In my case, the file permissions were too restrictive, so I couldn't read the file.

    Adding read+write permissions to the file before accessing it solved it.

    do {
        // Retrieve any existing attributes
        var attrs = try FileManager.default.attributesOfItem(atPath: stringpath)
        let existing = (attrs as NSDictionary).filePosixPermissions()
        // Set the read+write value in the attributes dict
        attrs[.posixPermissions] = existing | 0b110000000
        // Update attributes
        try FileManager.default.setAttributes(attrs, ofItemAtPath: stringpath)
    
        // Read data from file
        let data = try Data(contentsOf: URL(fileURLWithPath: stringpath, isDirectory: false), options: .uncached)
        print("success: \(data.count)")
    } catch {
        print(error)
    }
    

    That works if you're in a folder with enough permissions, as you can change the files permissions even if you didn't had read permission on the file previously. This solution was applied at https://github.com/ZipArchive/ZipArchive/issues/293.

提交回复
热议问题