Search code examples
iosswiftswift3enumeratempmediaitem

How to use enumerateValues(forProperties:using:) method in MPMediaItem (Swift 3)


I am trying to receive number of properties of Now Playing item. Per Apple documentation:

Anytime the app accesses more than one property, enumerating over a set of property keys is more efficient than fetching each individual property.

So I tried to use their method:

func enumerateValues(forProperties properties: Set<String>, 
               using block: @escaping (String, Any, UnsafeMutablePointer<ObjCBool>) -> Void)

But I just cannot understand how it should be used.

My code:

//MARK: Properties
var allProperties: [String: Any]
var albumTitle: String?
var albumArtist: String?
var title: String?
var artist: String?
var artwork: UIImage?
var genre: String?
var lyrics: String?
var releaseDate: Date?
var playbackDuration: TimeInterval?
var rating: Int?
var assetURL: URL?
var isExplicitItem: Bool?
var isCloudItem: Bool?
var hasProtectedAsset: Bool?

let propertiesSet: Set<String> = [MPMediaItemPropertyAlbumTitle,
                          MPMedia​Item​Property​Album​Artist,
                          MPMediaItemPropertyTitle,
                          MPMedia​Item​Property​Artist,
                          MPMediaItemPropertyArtwork,
                          MPMedia​Item​Property​Genre,
                          MPMedia​Item​Property​Lyrics,
                          MPMedia​Item​Property​ReleaseDate,
                          MPMedia​Item​Property​Playback​Duration,
                          MPMedia​Item​Property​Rating,
                          MPMedia​Item​Property​Asset​URL,
                          MPMediaItemPropertyIs​Explicit,
                          MPMediaItemPropertyIs​Cloud​Item,
                          MPMediaItemPropertyHas​Protected​Asset]

func getAllMetadata() {
    allProperties = nowPlaying?.enumerateValues(forProperties: propertiesSet, 
                                using: //No idea what to put here
        -> [String: Any])
}

How to use it properly?


Solution

  • Finally I figured out how to use it. So I re-wrote my function as follows:

    func getAllMetadata() {
        var allProperties: [String: Any] = [:]
        nowPlaying?.enumerateValues(forProperties: propertiesSet, using: {key,value,_ in allProperties[key] = value})
    
        albumTitle = allProperties["albumTitle"] as? String
        //and so on
    }
    

    This documentation helps me to understand the proper usage - https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html