簡體   English   中英

從iOS Share Extension獲取PHAsset

[英]Get PHAsset from iOS Share Extension

我正在為我的iOS應用程序開發照片的共享擴展。 在擴展內部,我能夠從NSItemProvider成功檢索UIImage對象。

但是,我希望能夠與我的容器應用程序共享圖像,而不必將整個圖像數據存儲在我的共享用戶默認值中。 有沒有辦法獲得用戶在共享擴展中選擇的圖像的PHAsset(如果他們從他們的設備中選擇)?

照片框架上的文檔( https://developer.apple.com/library/ios/documentation/Photos/Reference/Photos_Framework/ )有一句話說“這種架構使得使用它的過程變得簡單,安全和高效來自多個線程或多個應用和應用擴展的相同資產。“

這條線讓我覺得有一種方法可以在擴展和容器應用程序之間共享相同的PHAsset,但我還沒有找到任何方法來做到這一點? 有沒有辦法做到這一點?

如果圖像是從照片應用程序共享的,您可以獲得PHAsset。 項目提供程序將為您提供包含圖像文件名的URL,您可以使用它來匹配PHAsset。

/// Assets that handle through handleImageItem:completionHandler:
private var handledAssets = [PHAsset]()

/// Key is the matched asset's original file name without suffix. E.g. IMG_193
private lazy var imageAssetDictionary: [String : PHAsset] = {

    let options = PHFetchOptions()
    options.includeHiddenAssets = true

    let fetchResult = PHAsset.fetchAssetsWithOptions(options)

    var assetDictionary = [String : PHAsset]()

    for i in 0 ..< fetchResult.count {
        let asset = fetchResult[i] as! PHAsset
        let fileName = asset.valueForKey("filename") as! String
        let fileNameWithoutSuffix = fileName.componentsSeparatedByString(".").first!
        assetDictionary[fileNameWithoutSuffix] = asset
    }

    return assetDictionary
}()

...

provider.loadItemForTypeIdentifier(imageIdentifier, options: nil) { imageItem, _ in
    if let image = imageItem as? UIImage {
      // handle UIImage
    } else if let data = imageItem as? NSData {
      // handle NSData 
    } else if let url = imageItem as? NSURL {
         // Prefix check: image is shared from Photos app
         if let imageFilePath = imageURL.path where imageFilePath.hasPrefix("/var/mobile/Media/") {
             for component in imageFilePath.componentsSeparatedByString("/") where component.containsString("IMG_") {

        // photo: /var/mobile/Media/DCIM/101APPLE/IMG_1320.PNG
        // edited photo: /var/mobile/Media/PhotoData/Mutations/DCIM/101APPLE/IMG_1309/Adjustments/FullSizeRender.jpg

                // cut file's suffix if have, get file name like IMG_1309.
                let fileName = component.componentsSeparatedByString(".").first!
                if let asset = imageAssetDictionary[fileName] {
                    handledAssets.append(asset)
                    imageCreationDate = asset.creationDate
                }
                    break
                }
            }
    }

僅當NSItemProvider為您提供格式為的URL時,此方法才有效:

file:///var/mobile/Media/DCIM/100APPLE/IMG_0007.PNG

對於您的所有資產並非總是如此,但如果它返回的URL如下:

file:///var/mobile/Media/PhotoData/OutgoingTemp/2AB79E02-C977-4B4A-AFEE-60BC1641A67F.JPG

然后PHAsset將永遠找不到您的資產。 此外,后者是您的文件的副本,因此如果您碰巧有一個非常大的圖像/視頻,iOS將在該OutgoingTemp目錄中復制它。 在文檔中沒有任何地方說它什么時候會被刪除,希望很快就會被刪除。

我認為這是Apple在Sharing Extensions和PHPhotoLibrary框架之間留下的一個巨大差距。 Apple應該很快創建一個API來關閉它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM