How do I get photos from a PHAsset fetch?

1.3k views Asked by At

I can't get actual photos via a metadata list of photos from a PHAsset fetch. Ultimately I want an array of photos.

Here's my code (with last minute casting to UIImage at the last line before return):

enter image description here

Here are some outputs:

(lldb) po rec
<PHMoment: 0x7f8c03d62820> 12A0DFC9-5B8C-4E25-A373-122A5F1E1D8A/L0/060 (null) assetCollectionType=3/0 [2014-07-14 04:28:16 +0000 - 2014-07-14 04:28:18 +0000]

(lldb) po fetchResult
<PHFetchResult: 0x7f8c03d292c0> count=5

(lldb) po firstObject
(instance_type = Builtin.RawPointer = 0x00007f8c03d8bce0 -> 0x0000000100e83170 (void *)0x0000000100e83288: PHAsset)
 {
  instance_type = 0x00007f8c03d8bce0 -> 0x0000000100e83170 (void *)0x0000000100e83288: PHAsset
}
(lldb) po lastObject
(instance_type = Builtin.RawPointer = 0x00007f8c03d88be0 -> 0x0000000100e83170 (void *)0x0000000100e83288: PHAsset)
 {
  instance_type = 0x00007f8c03d88be0 -> 0x0000000100e83170 (void *)0x0000000100e83288: PHAsset
}
(lldb) po myPhoto
 (instance_type = Builtin.RawPointer = 0x00007f8c03d8b570 -> 0x0000000100e83170 (void *)0x0000000100e83288: PHAsset)
(lldb)

This doesn't do me much good.
I want to collect actual UIImages.

So I attempted to do a cast:

let myPhoto: AnyObject = fetchResult.objectAtIndex(1)! as UIImage

But that give me a runtime crash/error: enter image description here

Question: How do I collect actual UIImages from my fetch?

1

There are 1 answers

0
CamQuest On

Here's how:

if url.hasPrefix("assets-library://asset") {
     let localIdentifier = url.componentsSeparatedByString("=")[1].componentsSeparatedByString("&")[0]
     let fetchResult = PHAsset.fetchAssetsWithLocalIdentifiers([localIdentifier], options: nil)

    if fetchResult.count > 0 {
        if let asset = fetchResult.firstObject as? PHAsset {
            PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: CGSize(width: 64, height: 64), contentMode: PHImageContentMode.Default, options: nil, resultHandler: { (image:UIImage?, info:[NSObject:AnyObject]?) -> Void in
                self.imageButton.setImage(image, forState: .Normal)
            })
        }
    }
}