LoginSignup
22
22

More than 5 years have passed since last update.

Photos.framework でフォトライブラリから最新の写真を取得する

Posted at

写真を扱うアプリでは、『ライブラリから選択』『写真を撮る』という選択肢を用意するのが普通ですが、そのほかに『最新の写真を使う』という選択肢も用意しておくと便利です。
ここでは iOS の Photos.framework を使ってフォトライブラリから最新の写真を取得する方法を紹介します。

screenshot.jpg

サンプルコード

var fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(
    .SmartAlbum,
    subtype: .SmartAlbumUserLibrary,
    options: nil
)

guard let assetCollection = fetchResult.firstObject as? PHAssetCollection else {
    return
}

let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: options)

guard let latestAsset = fetchResult.firstObject as? PHAsset else {
    return
}

// latestAsset を使う

解説

まずは PHAssetCollectionfetchAssetCollectionsWithType:subtype:options: というメソッドで写真のコレクションを取得します。
サンプルコードでは type.SmartAlbum を、subtype.SmartAlbumUserLibrary を指定しているので、いわゆる『カメラロール』から写真を取得することになります。
別のアルバムから取得したい場合は、この typesubtype の組み合わせを変更する必要があります。

組み合わせについてはこちらが参考になります: (iOS8.1)PhotoKitで各種アルバムを取得する

var fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(
    .SmartAlbum,
    subtype: .SmartAlbumUserLibrary,
    options: nil
)

guard let assetCollection = fetchResult.firstObject as? PHAssetCollection else {
    return
}

次に、PHAssetfetchAssetsInAssetCollection:options: でコレクションから写真を取得します。
このとき、PHFetchOptionssortDiscriptor にディスクリプタをセットすることで、写真をどのような順番で取得するかを指定できます。
サンプルコードでは写真を作成日で降順にソートするよう指定しています。
あとは取得結果の最初の要素を取り出せば、それが最新の写真になっているというわけです。

let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: options)

guard let latestAsset = fetchResult.firstObject as? PHAsset else {
    return
}

// latestAsset を使う
22
22
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
22
22