0

I am saving (mediaItemCollection.items.first?.assetURL!.absoluteString) to local SQLite DB as String. Now I want to create MPMediaItem object back from saved string i.e assetURL!.absoluteString, Is it possible to create MPMediaItem object from its assesURL? If it is not possible then what should I save to SQLite DB so that I can create object of MPMediaItem back from saved property?

Afsar edrisy
  • 1,985
  • 12
  • 28
  • 1
    For a local file URL `absoluteString` is the wrong API anyway. – vadian Jan 02 '20 at 12:35
  • `assetURL` contains `persistentID`, and you may query by it. But you definetely should store some other info instead of `url` – user28434'mstep Jan 02 '20 at 12:46
  • hey @user28434 and @vadian any Idea what should use instead of ```absoluteString``` ? – Afsar edrisy Jan 02 '20 at 13:16
  • In my project I'm saving info about song itself. Like `Name` and `Artists`, etc. But only because in my project user can share info about media between their devices, and `persistentID`(and `assetURL`) are completely different on different devices. And I'm using it to query `MPMediaItem`. But in your case, if "reference" to the media will never leave the device you can just store `persistentID`. – user28434'mstep Jan 02 '20 at 13:21
  • Hey @user28434 Can you explain how to query by ```persistentID```? I could not find the way to do that. – MADHAVI KUMARI Jan 03 '20 at 05:38
  • Using [MPMediaQuery](https://developer.apple.com/documentation/mediaplayer/mpmediaquery) with [MPMediaItemPropertyPersistentID](https://developer.apple.com/documentation/mediaplayer/mpmediaitempropertypersistentid) in the predicate. – user28434'mstep Jan 03 '20 at 09:09
  • Thanks @user28434 I solved the problem from your suggestion. – Afsar edrisy Jan 03 '20 at 11:15

1 Answers1

2

I have find the solution from @user28434 suggestion.

I am saving persistentID to SQLite DB as String

 let songItem = mediaItemCollection.representativeItem!
 let persistantID = String(songItem.persistentID)

From this persistentID I am able to create MPMediaItem object back using MPMediaQuery while fetching stored persistentID from DB.

Following way to create MPMediaItem object.

 let noCloudPre = MPMediaPropertyPredicate(value: NSNumber(booleanLiteral: false),
                                              forProperty: MPMediaItemPropertyIsCloudItem)

    func getSongItem(persistantID: String) -> MPMediaItem?{
        let songQuery = MPMediaQuery.songs()
        songQuery.addFilterPredicate(noCloudPre)
        songQuery.addFilterPredicate(MPMediaPropertyPredicate(value: persistantID,
                                    forProperty: MPMediaItemPropertyPersistentID,
                                    comparisonType: MPMediaPredicateComparison.equalTo))
        return songQuery.items?[0]
    }

Afsar edrisy
  • 1,985
  • 12
  • 28