mafioso mafioso - 4 months ago 49
iOS Question

Check if fetched object using PHAsset is Image or Video in Swift

I want to check what type the latestObject is. Here's some code:

allMedia = PHAsset.fetchAssetsWithOptions(fetchOptions)
let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
let allVideo = PHAsset.fetchAssetsWithMediaType(.Video, options: fetchOptions)
print("Found \(allMedia.count) media")
print("Found \(allPhotos.count) images")
print("Found \(allVideo.count) videos")

let latestObject: AnyObject! = allMedia.lastObject

// How to check what type latestObject is?
// I think something with mediaType but how is it exactly going?

Answer

Have you tried something like this:

if let asset = allMedia.lastObject as? PHAsset {
    switch asset.mediaType {
    case .Image:
        print("Image")
    case .Video:
        print("Video")
    case .Audio:
        print("Audio")
    default:
        print("Unknown")
    }
}

Each element contained in the PHFetchResult is a PHAsset (in this case). So, with casting to PHAsset, you can access the property mediaType.