swiftmpmediaitemmpmediapickercontrollermpmediaitemcollection

How to create MPMediaItem from assetURL!.absoluteString?


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?


Solution

  • 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]
        }