user3395936
user3395936

Reputation: 681

The file “ ” couldn’t be opened because you don’t have permission to view it

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"}}

Upvotes: 14

Views: 19742

Answers (3)

Pratik Gondaliya
Pratik Gondaliya

Reputation: 430

I ran into an issue when trying to create a thumbnail from a video file on iOS. The error was caused by the app not having proper access to the selected file.

The fix? I had to call url.startAccessingSecurityScopedResource() before actually using the file. Here’s what worked for me:

// ✅ Start accessing the security-scoped resource (iOS only)
let accessGranted = false;

if (Platform.OS === "ios" && video.path.startsWith("file://")) {
  accessGranted = video.path.startAccessingSecurityScopedResource();
  
  if (!accessGranted) {
    throw new Error("Failed to access security-scoped resource.");
  }
}

Reference

Upvotes: 0

Ivan Vavilov
Ivan Vavilov

Reputation: 1649

Try

fileURL.startAccessingSecurityScopedResource()
//...
fileURL.stopAccessingSecurityScopedResource()

Upvotes: 39

Matt_S
Matt_S

Reputation: 315

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

Upvotes: 8

Related Questions