没有查看打开操作时从iOS文档提供程序返回的文档的权限



我正在iOS 9.2中创建一个文件/文档提供程序,导入和导出操作运行良好。然而,Open操作给我带来了麻烦。

我的文档提供商将一个示例文件写入其文件提供商存储,特别是在以下位置:

/private/var/mobile/Containers/Shared/AppGroup/41EDED34-B449-4FE0-94BA-4046CC573544/File Provider Storage/test.txt

我已经能够从文档提供程序中读取并验证数据是否正确。然而,当我试图读回传递给主机应用程序的URL时,我得到了一个权限错误:

Error Domain=NSCocoaErrorDomain Code=257 "The file “test.txt” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/41EDED34-B449-4FE0-94BA-4046CC573544/File Provider Storage/test.txt, NSUnderlyingError=0x15eda7700 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

我正在使用相当简单的代码进行阅读和写作,但如果相关的话,我会在这里包括它:

文件写入:(在我调用disstGrantingAccessToURL:之前在文档提供程序中调用)

NSString *contents = @"this is a dynamically created text file";
NSLog(@"write to file = %@", fileName);
NSError *err;
[contents writeToFile:fileName 
          atomically:NO 
            encoding:NSStringEncodingConversionAllowLossy 
                error:&err];

文件读取:(在documentPicker中的主机应用程序内部调用:didPickDocumentAtURL:)

NSString *readback = [[NSString alloc] initWithContentsOfFile:[url path]
                                                    usedEncoding:nil
                                                        error:&err];

我从苹果的示例代码开始,并阅读了他们的文档,但没能解释为什么失败。

对于我的文件提供程序,只调用init:函数。我不确定这是否正常,或者是否应该为Open操作调用其他方法。这是我的init:代码

- (instancetype)init {
    self = [super init];
    if (self) {
        [self.fileCoordinator coordinateWritingItemAtURL:[self documentStorageURL] options:0 error:nil byAccessor:^(NSURL *newURL) {
            // ensure the documentStorageURL actually exists
            NSError *error = nil;
            [[NSFileManager defaultManager] createDirectoryAtURL:newURL withIntermediateDirectories:YES attributes:nil error:&error];
        }];
    }
    return self;
}

我已经验证了上面的错误为零,新的URL如下:

file:///private/var/mobile/Containers/Shared/AppGroup/41EDED34-B449-4FE0-94BA-4046CC573544/File%20Provider%20Storage/

更新:我开始理解为什么主机应用程序无法读取文件。我想这是因为我没有托管应用程序中该应用程序组的权限。然而,我认为尝试添加此权限是没有意义的,因为宿主应用程序应该与任何支持适当扩展的文档提供商合作。

我想我的文件提供程序没有被调用的原因(除了它的init:)是因为"open"返回的文件被检测到是本地的,所以不需要复制。要传递本地文件,文档中说您必须传递documentStorageURL中的URL,但(根据定义?)该URL将映射到主机应用程序无法访问的应用程序组。

所以我不确定这将如何运作。如果有人能澄清我在这里应该做什么,我将不胜感激

在对文档进行进一步挖掘后,我终于发现了问题:在尝试访问URL之前,我需要调用URL上的"startAccessingSecurityScopedResource"。

请参阅本文档中"访问沙箱外的文件"的"要求"部分:

https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/AccessingDocuments/AccessingDocuments.html

接受的答案是正确的,这里只是一个即时代码:

    guard filePath.startAccessingSecurityScopedResource(), 
          let data = try? Data(contentsOf: filePath) else { return }
    filePath.stopAccessingSecurityScopedResource()
    // Do your business

最新更新