4

我想将文件从 iOS 11 文件应用程序复制到我的本地应用程序沙箱。出于测试目的,假设文件在文件应用程序中本地可用(从 iCloud 下载到本地存储)。文件扩展名已在我的应用程序中注册,当在 Files 应用程序中按下文件时,我的应用程序会从 Files 应用程序接收文件 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"}}

获得对外部文件的读取权限是否需要一些特殊的东西?

问候,

4

2 回答 2

7

这是您如何访问文件并在完成后停止的方法。

//To gain access
[nsUrl startAccessingSecurityScopedResource]

//To stop access
[nsUrl stopAccessingSecurityScopedResource]
于 2017-11-22T12:19:00.907 回答
-1

我有同样的问题将文件从 iOS 11 文件应用程序复制到沙箱。最后我解决了我的问题这个链接 在这里检查

和示例代码。

[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];

                }];
于 2018-04-13T12:52:13.690 回答