Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.


Photo Stream と PHAsset.fetchAssetsWithALAssetURLs の甘く切ない関係

- http://qiita.com/onizine/items/69b6cd4292add3cbadc0
- http://stackoverflow.com/questions/26588496/loading-image-from-my-photo-stream-using-uiimagepicker-results-url-and-phasset

単にfor文で回したくない :weary: というだけです。

    class func fetchAssetWithALAssetURL (alURL: NSURL) -> PHAsset? {
        var phAsset : PHAsset?

        let optionsForFetch = PHFetchOptions()
        optionsForFetch.includeHiddenAssets = true

        let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([alURL], options: optionsForFetch)
        if fetchResult.count > 0 {
            return fetchResult[0] as? PHAsset
        let str = alURL.absoluteString
        let localIDFragment = str.componentsSeparatedByString("=")[1].componentsSeparatedByString("&")[0]

        let fetchResultForPhotostream = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.AlbumMyPhotoStream, options: nil)
        if fetchResultForPhotostream.count > 0 {
            let photostream = fetchResultForPhotostream[0] as! PHAssetCollection
            let fetchResultForPhotostreamAssets = PHAsset.fetchAssetsInAssetCollection(photostream, options: optionsForFetch)
            if fetchResultForPhotostreamAssets.count >= 0 {
                let i=NSIndexSet(indexesInRange: NSRange(location: 0,length: fetchResultForPhotostreamAssets.count))
                // 逆順で列挙する。フォトストリームが後から表示されているのでその方が効率的のはず
                    options: NSEnumerationOptions.Reverse,
                    usingBlock: {
                        (obj, idx, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
                        let target = obj as! PHAsset
                        let ident = target.localIdentifier
                        if let _ = ident.rangeOfString(localIDFragment) {
                            phAsset = target
                            stop.memory = true
                return phAsset
        return nil

ポイントとしては、パラメータで渡す NSIndexSet の設定と、見つかった際に途中終了する方法でしょうか。stopをどうすれば良いのかというところがわかりにくかった。

Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What is going on with this article?