0

I want to build an Audiobookplayer which can set Bookmarks. Loading the Audiobooks from my Library with MPMediaQuery works fine, but when I take an audiobook off through iTunes, it stays in my realmfile.

I would like realm to delete the entry automatically when the playlist is updated through iTunes, but I can't seem to figure out how.

Here is my code.

class Books: Object {

dynamic var artistName: String?
dynamic var albumTitle: String?
dynamic var artwork: NSData?
dynamic var albumUrl: String?

dynamic var persistentID: String?

let parts = List<BookParts>()

override static func primaryKey() -> String? {
    return "persistentID"
}

override class func indexedProperties() -> [String] {
    return ["albumTitle"]
}

convenience init(artistName: String, albumTitle: String, albumUrl: String) {
    self.init()
    self.artistName = artistName
    self.albumTitle = albumTitle
    self.albumUrl = albumUrl
}


class BookQuery {

let realm = try! Realm()
var bookItems = Array<Books>()
var partItems = Array<BookParts>()

func getBooks() {

    let query: MPMediaQuery = MPMediaQuery.audiobooks()
    query.groupingType = .album
    let collection: [MPMediaItemCollection] = query.collections!

    try! realm.write {

        for allbooks in collection {
            let item = allbooks.representativeItem
            let book = Books()

            let id = item?.value(forProperty: MPMediaItemPropertyAlbumPersistentID) as! Int

            book.artistName = item?.artist
            book.albumTitle = item?.albumTitle
            book.albumUrl = item?.assetURL?.absoluteString
            book.artwork = Helper.getArtwork(item?.artwork) as NSData?
            book.persistentID = id.stringValue

            realm.add(book, update: true)

            guard realm.object(ofType: Books.self, forPrimaryKey: "persistentID") != nil else {
                continue
            }
            bookItems.append(book)

            }
        }
    }
}

I calling the MediaQuery in "viewDidLoad" in my LibraryViewController. I am pretty new to coding and are trying to solve this for a while. Thanks for any help.

cmag0505
  • 13
  • 4

1 Answers1

0

The high level thing you'll need to do is to have a way to detect when the iTunes playlist is updated and then delete the removed items' corresponding objects from the Realm.

A general approach to this is to get all the "persistent ID"s currently in the Realm at the start of the for loop, put those in an array, remove each ID it sees from the array, then delete objects with the persistent ID in the array that's left, since those weren't in the collection.

jpsim
  • 14,329
  • 6
  • 51
  • 68