iosswift2mpmediaitemmpmediaquerympmediaitemcollection

Finding a Song from Persistent ID using Swift 2 programming


I am a beginner with Swift programming who is trying to re-write code that I found online that Finds A Song from Persistent ID. The original code is found at this website:

http://www.ios-developer.net/iphone-ipad-programmer/development/songs-and-playlists/find-song-from-persistent-id

I want to write this code in Swift 2 (I won't use Objective-C), but I lack the knowledge and experience to translate it.

The code:

MPMediaItem *song;
MPMediaPropertyPredicate *predicate;
MPMediaQuery *songQuery;

predicate = [MPMediaPropertyPredicate predicateWithValue: MyPersistentIdString forProperty:MPMediaItemPropertyPersistentID];
songQuery = [[MPMediaQuery alloc] init];
[songQuery addFilterPredicate: predicate];
if (songQuery.items.count > 0)
{
//song exists
song = [songQuery.items objectAtIndex:0];
CellDetailLabel = [CellDetailLabel stringByAppendingString:[song valueForProperty: MPMediaItemPropertyTitle]];
}

My questions:

1) Is this code re-writeable to Swift, is it still current enough without depreciations?

2) How would I go about calling this code using a function?


Solution

  • Yes, we can rewrite this in Swift. To find if something is deprecated, check the Apple Documentation for MPMediaItem and MPMediaQuery. If the class or some of it's methods are deprecated it will be noted there.

    Here's the code rewritten in Swift as a function. It passes in the persistentIdString and returns an optional MPMediaItem

    func findSongWithPersistentIdString(persistentIDString: String) -> MPMediaItem? {
        let predicate = MPMediaPropertyPredicate(value: persistentIDString, forProperty: MPMediaItemPropertyPersistentID)
        let songQuery = MPMediaQuery()
        songQuery.addFilterPredicate(predicate)
    
        var song: MPMediaItem?
        if let items = songQuery.items, items.count > 0 {
             song = items[0]
        }
        return song
    }