Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It turns out there's a "using" function that tells the app its accessing files outside of it's sandbox. The methods startAccessingSecurityScopedResource and stopAccessingSecurityScopedResource on NSURL need to be wrapped around the code using the url, like so:

BOOL isAcccessing = [url startAccessingSecurityScopedResource];
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);
}
if (isAccessing) {
    [url stopAccessingSecurityScopedResource];
}

I'm not sure if there's anything specific to iOS 13 that requires this when it didn't previously, but that is the only real change between it working and not working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...