2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-03-17

内容的には、下のリンクと同じ内容です。ちょっと違うやり方をしたというだけ。なぜPHAsset.fetchAssetsWithALAssetURLsがPhotoStreamの場合だけきちんと値を返却してくれないのかと。。

単に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))
				// 逆順で列挙する。フォトストリームが後から表示されているのでその方が効率的のはず
				fetchResultForPhotostreamAssets.enumerateObjectsAtIndexes(i,
					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) {
							LOG("found!")
							phAsset = target
							stop.memory = true
						}
				})
				return phAsset
			}
		}
		return nil
	}

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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?