【问题标题】:iOS 11 DropInteraction Session from Photos returns invalid file path来自照片的 iOS 11 DropInteraction Session 返回无效的文件路径
【发布时间】:2021-12-23 10:37:27
【问题描述】:

当将图像从 Photos 应用程序放入我的自定义应用程序时,- (void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session 我收到一个 NSURL*,其 [url absoluteString] 采用以下形式:

file:///var/tmp/com.apple.DragUI.druid/.com.apple.DragUI.4tyFQQ/version=1&uuid=FF693BFB-99FF-4790-BBF2-A226593F718D&mode=compatible.png

每当我尝试使用此文件路径时,都会收到 The file couldn’t be opened because there is no such file 错误。这是有道理的,因为路径本身看起来不正常。我看到 other implementations 表明这些可能应该采用更符合预期的路径格式。

万一读取问题与访问权限相关,我可以成功地包装操作:

BOOL success = [url startAccessingSecurityScopedResource] /* begin */;

// ...

if (success) {
  [url stopAccessingSecurityScopedResource] /* terminate */;
}

但这不会影响响应数据。该应用程序目前还可以在拖放之外的其他用户旅程中成功读取和写入图片库,因此在我看来这与缺少权限无关。

相比之下,我可以处理从 Brave 浏览器通过 performDrop 传递的 NSConcreteData 类型而不会出错。

有人知道发生了什么吗?有什么方法可以规范化这个提供的 URI,以便我可以正确解析文件,或者它可能表示错误的应用程序状态?

我在物理 iPad 上运行 iOS 14

【问题讨论】:

    标签: ios objective-c drag-and-drop


    【解决方案1】:

    尝试直接从 url 解析而不是尝试从absoluteString 加载它,像这样:

    // given an NSURL object `url`
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    

    编辑:

    UIDropInteractionDelegate 我正在使用的实现

    - (BOOL)dropInteraction:(UIDropInteraction *)interaction canHandleSession:(id<UIDropSession>)session {
        return [session canLoadObjectsOfClass:[UIImage class]];
    }
    
    - (UIDropProposal *)dropInteraction:(UIDropInteraction *)interaction sessionDidUpdate:(id<UIDropSession>)session {
        return [[UIDropProposal alloc] initWithDropOperation:UIDropOperationCopy];
    }
    
    - (void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session {
        UIDragItem *item = session.items[0];
        NSArray *typeIdentifiers = item.itemProvider.registeredTypeIdentifiers;
        [item.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifiers[0]
                                                 completionHandler:^(NSURL * _Nullable url,
                                                                     NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSData *data = [NSData dataWithContentsOfURL:url];
                UIImage *image = [UIImage imageWithData:data];
                // use image...
            });
        }];
    }
    

    【讨论】:

    • 您好,非常感谢您的帮助。不幸的是,这不起作用。对dataWithContentsOfURL 的调用返回(null)
    • @Mapsy 我更新了我的答案,如果你想仔细检查你是如何实现这些委托方法的(测试从照片应用程序拖动)
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多