mafioso mafioso - 1 year ago 212
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 Source

Have you tried something like this:

if let asset = allMedia.lastObject as? PHAsset {
    switch asset.mediaType {
    case .Image:
    case .Video:
    case .Audio:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download