Скопируйте файл из приложения iOS 11 Files в песочницу

Я хочу скопировать файл из приложения «Файлы» iOS 11 в изолированную программную среду моего локального приложения. В целях тестирования предполагается, что файл локально доступен в приложении «Файлы» (загружен из iCloud в локальное хранилище). Расширение файла зарегистрировано в моем приложении, и когда файл нажимается в приложении «Файлы», мое приложение получает URL-адрес файла из приложения «Файлы»:

NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];

NSURL *nsUrl; // comes from Files app. For instance "file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/test.rar"
NSURL *targetUrl; // file in my app's document directory

NSError *coordinatorError = nil;
[fileCoordinator coordinateReadingItemAtURL:nsUrl options:NSFileCoordinatorReadingWithoutChanges error:&coordinatorError byAccessor:^(NSURL *newURL) 
{   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //if ([fileManager fileExistsAtPath: [nsUrl path]])
    {
        NSLog(@"Copy from %@ to %@", newURL, targetUrl);

        NSError *copyError = nil;
        [fileManager copyItemAtURL:newURL toURL:targetUrl error:&copyError];
        if (!copyError)
        {
            // OK
        }
        else
        {
            NSLog(@"Files app error: %@", copyError);
        }
    }
}];

Но операция завершается с ошибкой с этим выводом:

2017-11-22 09:30:28.685127+0100 test[434:40101] Copy from file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/test.rar
 to file:///var/mobile/Containers/Data/Application/01BB33E6-2790-0FD0-8270-000/Documents/test.rar
2017-11-22 09:30:28.687174+0100 test[434:40101] Files app error: Error Domain=NSCocoaErrorDomain Code=257 "The file “test.rar” couldn’t be 
opened because you don’t have permission to view it." 
UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/test.rar, 
NSUnderlyingError=0x1c084abf0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

Требуется ли что-то особенное, чтобы получить доступ для чтения к внешнему файлу?

С уважением,


person Hyndrix    schedule 22.11.2017    source источник


Ответы (2)


Вот как вы можете получить доступ к файлам и остановиться, когда закончите с этим.

//To gain access
[nsUrl startAccessingSecurityScopedResource]

а также

//To stop access
[nsUrl stopAccessingSecurityScopedResource]
person Hyndrix    schedule 22.11.2017
comment
Вы можете поместить его в блок coordinateReadingItemAtURL. И не забудьте вызвать ''stopAccessingSecurityScopedResource'', когда закончите. - person Hyndrix; 19.12.2017

У меня такая же проблема с копированием файла из приложения iOS 11 Files в песочницу. наконец, я решил свою проблему по этой ссылке проверьте здесь

и пример кода.

[fileURL startAccessingSecurityScopedResource];//fileURL ---> Which FileURL you want to copy

                NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];

                NSFileAccessIntent *readingIntent = [NSFileAccessIntent readingIntentWithURL:fileURL options:NSFileCoordinatorReadingWithoutChanges];

                [fileCoordinator coordinateAccessWithIntents:@[readingIntent] queue:[NSOperationQueue mainQueue] byAccessor:^(NSError *error) {

                    NSData *filePathData;

                    if (!error)
                    {
                        // Always get URL from access intent. It might have changed.
                        NSURL *safeURL = readingIntent.URL;

                     // here your code to do what you want with this 

                    }

                    [fileURL stopAccessingSecurityScopedResource];

                }];
person Murugan M    schedule 13.04.2018