ios - How to retrieve data from NSUserDefaults? -
currently, try make music playlist application. try save , retrieve playlist data nsuserdefaults. have no problem when saving data got error when retrieving data.
i got:
terminating app due uncaught exception 'mpmediaitemcollectioninitexception', reason: '-init not supported, use -initwithitems:
i'm following answer play ipod playlist retrieved saved persistentid list try write in swift.
here save function:
func saveplaylist(var mediaitemcollection: mpmediaitemcollection){ var items: nsarray = mediaitemcollection.items var listtosave: nsmutablearray = nsmutablearray() song in items{ var persistentid: anyobject! = song.valueforproperty(mpmediaitempropertypersistentid) listtosave.addobject(persistentid) } var data: nsdata = nskeyedarchiver.archiveddatawithrootobject(listtosave) nsuserdefaults.standarduserdefaults().setobject(data, forkey: "songslist") nsuserdefaults.standarduserdefaults().synchronize() }
and here retrieve function:
func setupmusic(){ if nsuserdefaults.standarduserdefaults().objectforkey("songslist") != nil{ var thelist: nsmutablearray = nsmutablearray() var data: nsdata = (nsuserdefaults.standarduserdefaults().objectforkey("songslist") as? nsdata)! var decodeddata: nsarray = (nskeyedunarchiver.unarchiveobjectwithdata(data) as? nsarray)! thelist.addobjectsfromarray(decodeddata [anyobject]) var allthesongs: nsmutablearray = nsmutablearray() var = 0; < thelist.count; i++ { var songquery = mpmediaquery.songsquery() var songs: nsarray = songquery.items allthesongs.addobject(songs) } var currentqueue: mpmediaitemcollection = mpmediaitemcollection() mymusicplayer?.setqueuewithitemcollection(currentqueue) }else{ println("fail!!!!!!!!!!!!") } }
how can fix it?
here issue var currentqueue: mpmediaitemcollection = mpmediaitemcollection()
you must init
items
as per documentation apple.
init(items:) designated initializer
initializes media item collection array of media items. declaration
swift
init!(items items: [anyobject]!) parameters items
the array of items assigning media item collection.
you have init items
var currentqueue: mpmediaitemcollection = mpmediaitemcollection(items:itemsarray)
Comments
Post a Comment