10
votes

I am downloading a file to a folder and I am validating that the file is indeed there in the code, but I am getting the above error. Can someone help me figure out why i dont have permissions to read this file?

let documentsURL = NSSearchPathForDirectoriesInDomains
(.DocumentDirectory, .UserDomainMask, true)[0]

let checkValidation = NSFileManager.defaultManager()

if (checkValidation.fileExistsAtPath(documentsURL))
{
    print("FILE AVAILABLE");
}
else
{
    print("FILE NOT AVAILABLE");
}

print(documentsURL)

do{
    let data = try String(contentsOfFile: documentsURL as String,
                          encoding: NSASCIIStringEncoding)
    print(data)
    
}
catch let error { print(error) }

Error Domain=NSCocoaErrorDomain Code=257 "The file “Documents” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/7FA4D6A9-2149-4053-BF08-22E94A00AE34/Documents, NSUnderlyingError=0x137807200 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}

2
I would consider printing the URL you cast to a String first, it most likely is not a good idea to use NSURL and String that way. Consider using NSURL.relativePath instead.Antwan van Houdt
@AntwanvanHoudt sorry i am not understanding what you want me to do? How do i use NSURL.relativePath? Besides this piece of code was running for me before as String, so I doubt that it is the issueuser3395936
"documentsDirectoryURL.relativePath!" instead of the cast.Antwan van Houdt
@AntwanvanHoudt gives me this error : ` Value of type 'String' has no member 'relativePath'`user3395936
If you would actually catch an error, this problem would become a lot simpler. The code would literally tell you what is wrong. catch let error { print(error) }nhgrif

2 Answers

23
votes

Try

fileURL.startAccessingSecurityScopedResource()
//...
fileURL.stopAccessingSecurityScopedResource()
8
votes

Your documentsURL is the address of the Documents FOLDER in your app. It is not a FILE that you can get the contents of:

/var/mobile/Containers/Data/Application/7FA4D6A9-2149-4053-BF08-22E94A00AE34/Documents