通过共享扩展无法打开/读取图像。

5

我正在尝试在应用程序扩展中获取图像。问题是当类型为“public.image”时,无法获取图像,但是当类型为“public.png”时成功了。我想要做的就是获取图像并上传到服务器。

这里是我正在使用的代码。

if let extensionContext = self.extensionContext,
        let item = extensionContext.inputItems.first as? NSExtensionItem,
        let attachment = item.attachments?.first as? NSItemProvider {

        guard let type: String = attachment.registeredTypeIdentifiers.first else { return } 
        // -> "public.png" or "public.image"
        attachment.loadFileRepresentation(forTypeIdentifier: type, completionHandler: { (url, error) in
            guard let url = url else { return }
            do {
                let imageData = try Data(contentsOf: url)
                if let image = UIImage(data: imageData) {
                    // some task with image
                } else {
                    // reach here!!!!!
                }
            } catch {
                print(error.localizedDescription)
            }
        })
    }

我检查了loadFileRepresentation()方法返回的url,当出现错误时,这个url看起来像这样:file:///private/var/mobile/Containers/Data/PluginKitPlugin/E82D4A01-A2ED-42E0-9378-420F5B1DBAD3/tmp/.com.apple.Foundation.NSItemProvider.5FKOVj/image

然后使用FileManager.default.attributesOfItem(atPath: url.path)方法返回的结果如下:

attributesOfFile: [__C.FileAttributeKey(_rawValue: NSFileOwnerAccountName): mobile,
 __C.FileAttributeKey(_rawValue: NSFilePosixPermissions): 420,
 __C.FileAttributeKey(_rawValue: NSFileSystemNumber): 16777219,
 __C.FileAttributeKey(_rawValue: NSFileReferenceCount): 1,
 __C.FileAttributeKey(_rawValue: NSFileSystemFileNumber): 1163851, 
 __C.FileAttributeKey(_rawValue: NSFileCreationDate): 2017-10-28 07:36:09 +0000,
 __C.FileAttributeKey(_rawValue: NSFileProtectionKey): NSFileProtectionCompleteUntilFirstUserAuthentication,
 __C.FileAttributeKey(_rawValue: NSFileType): NSFileTypeRegular, __C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountName): mobile,
 __C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountID): 501,
 __C.FileAttributeKey(_rawValue: NSFileModificationDate): 2017-10-28 07:36:09 +0000,
 __C.FileAttributeKey(_rawValue: NSFileSize): 1018925,
 __C.FileAttributeKey(_rawValue: NSFileExtensionHidden): 0,
 __C.FileAttributeKey(_rawValue: NSFileOwnerAccountID): 501]

供您参考,这是我在截屏后打开分享扩展的位置。 在此输入图片描述


多亏了这个问题,我终于得到了这张图片。https://dev59.com/k6Lia4cB1Zd3GeqPkIPg - Justin Sato
1个回答

2

谢谢@Hilmar。你的答案很完美。获取图片一次,获取url另一次,这真是非常奇怪。 - Justin Sato
嗨,是的 - 我也在想(尽管还有第三种方式,即原始数据)。可能是因为目前没有输入API。听起来像是一个缺失的功能或错误。 - Hilmar Demant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接