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,
MPMediaItemPropertyAlbumArtist,
MPMediaItemPropertyTitle,
MPMediaItemPropertyArtist,
MPMediaItemPropertyArtwork,
MPMediaItemPropertyGenre,
MPMediaItemPropertyLyrics,
MPMediaItemPropertyReleaseDate,
MPMediaItemPropertyPlaybackDuration,
MPMediaItemPropertyRating,
MPMediaItemPropertyAssetURL,
MPMediaItemPropertyIsExplicit,
MPMediaItemPropertyIsCloudItem,
MPMediaItemPropertyHasProtectedAsset]
func getAllMetadata() {
allProperties = nowPlaying?.enumerateValues(forProperties: propertiesSet,
using: //No idea what to put here
-> [String: Any])
}
How to use it properly?
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