Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get around NSCocoaErrorDomain:257 when pulling a file from the Files app?

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.

like image 766
Jordan Avatar asked Oct 03 '19 17:10

Jordan


1 Answers

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

like image 108
ramzesenok Avatar answered Oct 11 '22 14:10

ramzesenok