Permission Denied when trying to create a directory in Application Support

本秂侑毒 提交于 2020-01-24 00:35:13

问题


I'm trying to create a directory inside the Application Support Directory, but it fails every single time.

Here's the code:

func getDownloadableContentPath() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
        var directory = paths[0]
        directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: directory) {
            do {
               try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
            }
            catch {
               print("Error: Unable to create directory: \(error)")
            }
            var url = URL(fileURLWithPath: directory)
            var values = URLResourceValues()
            values.isExcludedFromBackup = true
            do {
                try url.setResourceValues(values)
            }
            catch {
                print("Error: Unable to exclude directory from backup: \(error)")
            }
        }
        return directory
    }

The Error is:

 Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “IAP” in the folder “Application%20Support”." UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/FF91E234-F856-492E-8C91-9EFAEA3735D4/Library/Application%20Support/IAP, NSUnderlyingError=0x174245430 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've tried changing the appending path component, tried the documents directory, all fail with the same error.


回答1:


The problem is in this line

directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString

This return filePath, while below function required simple path of directory.

fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)

So either change this line

directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString

with this line

directory = directory + "/IAP"

OR change same line with below line

let url = URL(fileURLWithPath: directory).appendingPathComponent("IAP")

and use this function to create directory

fileManager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)

Hope this helps you.



来源:https://stackoverflow.com/questions/45993238/permission-denied-when-trying-to-create-a-directory-in-application-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!