I'm trying to access a file to pull a copy into my app so that users can associate it with relevant information. It used to work just fine up until recently, and now I suddenly am getting the following message:
Failed to read file, error Error Domain=NSCocoaErrorDomain Code=257 "The file “[File name]” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/[File name], NSUnderlyingError=0x281b88690 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
This is the code that's throwing the error:
//AppDelegate.m
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if (![url.pathExtension isEqualToString:@"pdf"] && ![url.pathExtension isEqualToString:@"png"] && ![url.pathExtension isEqualToString:@"jpg"] && ![url.pathExtension isEqualToString:@"jpeg"]){
return false;
}
NSError* error = nil;
NSString *path = [url path];
NSData *data = [NSData dataWithContentsOfFile:path options: 0 error: &error];
if(data == nil) {
NSLog(@"Failed to read file, error %@", error);
}
//Do stuff with the file
return true;
}
I did update to xcode 11 and iOS 13, so there may have been a change there that I wasn't aware of.
Jordan has a great answer! Here's the version translated to Swift
let isAccessing = url.startAccessingSecurityScopedResource()
// Here you're processing your url
if isAccessing {
url.stopAccessingSecurityScopedResource()
}
As I encountered this myself and the comment to Jordan's answer confirmed this happens only on the real device. Simulator has no such an issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With