Using the iPod Library
2016-02-22 17:50
393 查看
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/UsingTheiPodLibrary/UsingTheiPodLibrary.html
Yourapplicationmayneedmorecontrolovermanagingandchoosingmediaitemsthanyougetwiththemediaitempicker.IfyouwanttoprovideacustomuserinterfacetothedeviceiPodlibrary,performspecificqueries,orassociatecustommetadatawithmedia
items,youneedthedatabaseaccessclassesofthisAPI.
Figure4-1illustrateshowyourapplicationandthedatabaseaccessclassesinteracttoretrievemediaitems.
Figure4-1UsingtheiPodlibrary
databaseaccessclasses
First,takeamomenttonoticethesimilaritybetweenthisfigureandFigure
1-5.Theearlierfigurehelpedexplainwhataqueryis.Thisfigureplacesthemediaqueryclassamongitscohorts,showinghowallthedatabaseaccessclassesrelatetoeachother.
ThefigureillustratestwoscenariosofinteractionbetweenyourapplicationandthedeviceiPodlibrary.First,movingcounterclockwisefromthe“Yourapplication”icon,thefiguredepictsthecreationandconfigurationofaquerythatinturndefinesamedia
itemcollection.Thecollectionpointstoaparticularsubsetofitemsfromthelibrary.Althoughnotshowninthefigure,thecollectionisthereturnvalueofinvokingthequery.Eachmediaitemownsamediaitemartworkobject,asshowninthefigure,among
itsotherproperties.
ThesecondscenarioinFigure4-1isyourapplicationreceivingchangenotificationsfromtheiPodlibrarybywayofthe
Byregisteringtoreceivethesechangenotifications,yourapplicationcanupdateanycacheoflibrarycontentifausersyncstheirdevicewhileyourapplicationisrunning.
RetrievingmediaitemsfromthedeviceiPodlibrarybeginswithconstructingamediaquery.Thesimplestqueryisthegeneric“
queryshowninListing4-1,whichmatchestheentirecontentsofthelibrary.TheexamplethenlogsthetitlesofthemediaitemstotheXcodedebugger
console,demonstratinguseofthe
Listing4-1Creatingandusingagenericmediaquery
Note:Aswithallcodeexamplesinthisdocument,thisexamplewillruncorrectlyonlyonaprovisionediPhonedevice,notintheSimulator.
Toconstructamorespecificquery,applyoneormoremediapropertypredicatestoagenericquery.Apredicatespecifiesasinglelogicalconditiontotestmediaitemsagainst.
Listing4-2createsapredicatecontainingtheconditionthatamediaitem’s“artist”propertymusthave
aparticularvalue.Thelistingthenaddsthepredicatetoaquery.
Listing4-2Constructingandapplyingamediapropertypredicate
Ifyouweretorunthiscode,the
librarythatarebyHappytheClown.
Youcanconstructandaddmultiplepredicatestoaquerytonarrowwhatthequerymatches.Listing4-3shows
thistechniqueusingtwopredicates.
Listing4-3Applyingmultiplepredicatestoanexistingmediaquery
Youconstructeachpredicateusingavalueofyourchoice(suchasanartist’sname)alongwiththeappropriatemediaitempropertykey.ThesekeysaredescribedinMPMediaItem
ClassReferencein
Whenyouapplymorethanonepredicatetoaquery,thequerycombinesthemusingthelogicalANDoperator.
Important:Donotapplymorethanonepredicateforaparticularmediaitemproperty.Forexample,donotspecifytwo
toaquery.Ifyoudo,theresultingbehavioruponusingthequeryisundefined.
Youcanalsoaddpredicatestoaqueryuponinitialization,asshowninListing4-4.(Thetwopredicates
inthisexampleareassumedtobepreviouslydefined.)
Listing4-4Applyingmultiplepredicateswheninitializingamediaquery
Listing4-4firstdefinesan
thatcontainstwopredicates,thenallocatesandinitializesamediaqueryusingthe
method.
Onlycertainpropertykeyscanbeusedtobuildvalidpredicates.Thesekeysaretaggedas“filterable”inMPMediaItem
ClassReference.Ifyouattempttouseaquerythatcontainsaninvalidpredicate,theresultingbehaviorisundefined.
Important:Thesystempermitsyoutocreatepredicatesusingpropertykeysthatarenotmeaningfulforusewithpredicates.Ifyouattempttoapplysuchapredicatetoaquery,
theresultingbehaviorisundefined.Toavoidproblemswithpredicates:
ReadtheMPMediaItem
ClassReferencedocumentationcarefully.
Codedefensivelybyusingthe
keysbeforeusingthem.
Don’tletusersdefinemediapropertypredicates.
Thoroughlytestyourcodetoensurethatitbehavesasyouexpectittoundervariousconditions.
Listing4-5showshowtousethe
methodtovalidateamediaitempropertykeybeforeusingitinapredicate.
Listing4-5Testingifapropertykeycanbeusedforamediapropertypredicate
InListing4-5,onlyiftheindicatedmediaitempropertykey(inthisexample,
canbeusedtoconstructavalidpredicatewillthebodyoftheifstatementexecute.Applerecommendsthatyoualwaysperformachecklikethisbeforeconstructingamediapropertypredicate.
Amediaqueryisusefulnotonlyforretrievingungroupedmediaitems.Youcanalsouseamediaquerytoretrievesortedandarrangedcollectionsofmediaitems.Thearrangementyougetdependsonthe
valueyousetforthemediaquery’s
Listing4-6showshowtoretrieveallthesongsbyaparticularartist,withthosesongsarrangedintoalbums.
TheexamplelogstheresultstotheXcodedebuggerconsole.
Listing4-6Usinggroupingtypetospecifymediaitemcollections
YoucanseeinListing4-6thatthevalueofthemediaquery’s
isanarrayofarrays.Theouterforloopiteratesoverthealbumsperformedthespecifiedartist.Theinnerforloopiteratesoverthesongsinthecurrentalbum.
The
includesseveralconvenienceconstructorsforcreatingqueriesthatarepreconfiguredwithagroupingtype.Thefollowingstatement,forexample,attachesthe“albums”groupingtypetoanewly-allocatedquery:
Fordescriptionsofalltheconvenienceconstructors,seeMPMediaQuery
ClassReference.
Oneofthemostusefulandhigh-impactpropertiesofamediaitemisitsartwork.Todisplayartwork,youuseInterfaceBuilderaswellasXcode.Thestepsareasfollows:
Adda
toyourviewlayoutinInterfaceBuilder.
AddanIBOutletinstancevariabletoyourviewcontrollerclasstoconnecttothe
Retrievetheartworkfromthemediaitemthatownsit(havingpreviouslyretrievedthemediaitemasdescribedinthischapter).
Converttheartworktoa
thenassignittoyourlayout’s
Listing4-7showshowtodosteps3and4.
Listing4-7Displayingalbumartworkforamediaitem
The
4-7isafallbackimagethatyouaddtoyourXcodeproject,forusewhenamediaitemhasnoassociatedartwork.
UsingtheiPodLibrary
Yourapplicationmayneedmorecontrolovermanagingandchoosingmediaitemsthanyougetwiththemediaitempicker.IfyouwanttoprovideacustomuserinterfacetothedeviceiPodlibrary,performspecificqueries,orassociatecustommetadatawithmediaitems,youneedthedatabaseaccessclassesofthisAPI.
Figure4-1illustrateshowyourapplicationandthedatabaseaccessclassesinteracttoretrievemediaitems.
Figure4-1UsingtheiPodlibrary
databaseaccessclasses
First,takeamomenttonoticethesimilaritybetweenthisfigureandFigure
1-5.Theearlierfigurehelpedexplainwhataqueryis.Thisfigureplacesthemediaqueryclassamongitscohorts,showinghowallthedatabaseaccessclassesrelatetoeachother.
ThefigureillustratestwoscenariosofinteractionbetweenyourapplicationandthedeviceiPodlibrary.First,movingcounterclockwisefromthe“Yourapplication”icon,thefiguredepictsthecreationandconfigurationofaquerythatinturndefinesamedia
itemcollection.Thecollectionpointstoaparticularsubsetofitemsfromthelibrary.Althoughnotshowninthefigure,thecollectionisthereturnvalueofinvokingthequery.Eachmediaitemownsamediaitemartworkobject,asshowninthefigure,among
itsotherproperties.
ThesecondscenarioinFigure4-1isyourapplicationreceivingchangenotificationsfromtheiPodlibrarybywayofthe
class.MPMediaLibrary
Byregisteringtoreceivethesechangenotifications,yourapplicationcanupdateanycacheoflibrarycontentifausersyncstheirdevicewhileyourapplicationisrunning.
RetrievingUngroupedMediaItems
RetrievingmediaitemsfromthedeviceiPodlibrarybeginswithconstructingamediaquery.Thesimplestqueryisthegeneric“everything”
queryshowninListing4-1,whichmatchestheentirecontentsofthelibrary.TheexamplethenlogsthetitlesofthemediaitemstotheXcodedebugger
console,demonstratinguseofthe
itemspropertytoinvokethequeryandretrievethemediaitemsitmatches.
Listing4-1Creatingandusingagenericmediaquery
MPMediaQuery*everything=[[MPMediaQueryalloc]init]; |
NSLog(@"Loggingitemsfromagenericquery..."); |
NSArray*itemsFromGenericQuery=[everythingitems]; |
for(MPMediaItem*songinitemsFromGenericQuery){ |
NSString*songTitle=[songvalueForProperty:MPMediaItemPropertyTitle]; |
NSLog(@"%@",songTitle); |
} |
Toconstructamorespecificquery,applyoneormoremediapropertypredicatestoagenericquery.Apredicatespecifiesasinglelogicalconditiontotestmediaitemsagainst.
Listing4-2createsapredicatecontainingtheconditionthatamediaitem’s“artist”propertymusthave
aparticularvalue.Thelistingthenaddsthepredicatetoaquery.
Listing4-2Constructingandapplyingamediapropertypredicate
MPMediaPropertyPredicate*artistNamePredicate= |
[MPMediaPropertyPredicatepredicateWithValue:@"HappytheClown" |
forProperty:MPMediaItemPropertyArtist]; |
MPMediaQuery*myArtistQuery=[[MPMediaQueryalloc]init]; |
[myArtistQueryaddFilterPredicate:artistNamePredicate]; |
NSArray*itemsFromArtistQuery=[myArtistQueryitems]; |
itemsFromArtistQueryarraywouldcontainonlythoseitemsfromtheiPod
librarythatarebyHappytheClown.
Youcanconstructandaddmultiplepredicatestoaquerytonarrowwhatthequerymatches.Listing4-3shows
thistechniqueusingtwopredicates.
Listing4-3Applyingmultiplepredicatestoanexistingmediaquery
MPMediaPropertyPredicate*artistNamePredicate= |
[MPMediaPropertyPredicatepredicateWithValue:@"SadtheJoker" |
forProperty:MPMediaItemPropertyArtist]; |
MPMediaPropertyPredicate*albumNamePredicate= |
[MPMediaPropertyPredicatepredicateWithValue:@"StairTumbling" |
forProperty:MPMediaItemPropertyAlbumTitle]; |
MPMediaQuery*myComplexQuery=[[MPMediaQueryalloc]init]; |
[myComplexQueryaddFilterPredicate:artistNamePredicate]; |
[myComplexQueryaddFilterPredicate:albumNamePredicate]; |
ClassReferencein
Generaland
MediaItemPropertyKeys
Podcast.
ItemPropertyKeys
Whenyouapplymorethanonepredicatetoaquery,thequerycombinesthemusingthelogicalANDoperator.
Important:Donotapplymorethanonepredicateforaparticularmediaitemproperty.Forexample,donotspecifytwo
MPMediaItemPropertyArtistpredicates
toaquery.Ifyoudo,theresultingbehavioruponusingthequeryisundefined.
Youcanalsoaddpredicatestoaqueryuponinitialization,asshowninListing4-4.(Thetwopredicates
inthisexampleareassumedtobepreviouslydefined.)
Listing4-4Applyingmultiplepredicateswheninitializingamediaquery
NSSet*predicates= |
[NSSetsetWithObjects:artistNamePredicate,albumNamePredicate,nil]; |
MPMediaQuery*specificQuery= |
[[MPMediaQueryalloc]initWithFilterPredicates:predicates]; |
objectNSSet
thatcontainstwopredicates,thenallocatesandinitializesamediaqueryusingthe
classinitWithFilterPredicates:
method.
Onlycertainpropertykeyscanbeusedtobuildvalidpredicates.Thesekeysaretaggedas“filterable”inMPMediaItem
ClassReference.Ifyouattempttouseaquerythatcontainsaninvalidpredicate,theresultingbehaviorisundefined.
Important:Thesystempermitsyoutocreatepredicatesusingpropertykeysthatarenotmeaningfulforusewithpredicates.Ifyouattempttoapplysuchapredicatetoaquery,
theresultingbehaviorisundefined.Toavoidproblemswithpredicates:
ReadtheMPMediaItem
ClassReferencedocumentationcarefully.
Codedefensivelybyusingthe
canFilterByProperty:methodtovalidatemediaitemproperty
keysbeforeusingthem.
Don’tletusersdefinemediapropertypredicates.
Thoroughlytestyourcodetoensurethatitbehavesasyouexpectittoundervariousconditions.
Listing4-5showshowtousethe
canFilterByProperty:class
methodtovalidateamediaitempropertykeybeforeusingitinapredicate.
Listing4-5Testingifapropertykeycanbeusedforamediapropertypredicate
if([MPMediaItemcanFilterByProperty:MPMediaItemPropertyGenre]){ |
MPMediaPropertyPredicate*rockPredicate= |
[MPMediaPropertyPredicatepredicateWithValue:@"Rock" |
forProperty:MPMediaItemPropertyGenre]; |
[queryaddFilterPredicate:rockPredicate]; |
} |
MPMediaItemPropertyGenre)
canbeusedtoconstructavalidpredicatewillthebodyoftheifstatementexecute.Applerecommendsthatyoualwaysperformachecklikethisbeforeconstructingamediapropertypredicate.
RetrievingMediaItemCollections
Amediaqueryisusefulnotonlyforretrievingungroupedmediaitems.Youcanalsouseamediaquerytoretrievesortedandarrangedcollectionsofmediaitems.Thearrangementyougetdependsonthevalueyousetforthemediaquery’s
groupingproperty.
Listing4-6showshowtoretrieveallthesongsbyaparticularartist,withthosesongsarrangedintoalbums.
TheexamplelogstheresultstotheXcodedebuggerconsole.
Listing4-6Usinggroupingtypetospecifymediaitemcollections
MPMediaQuery*query=[[MPMediaQueryalloc]init]; |
[queryaddFilterPredicate:[MPMediaPropertyPredicate |
predicateWithValue:@"MoribundtheSquirrel" |
forProperty:MPMediaItemPropertyArtist]]; |
//Setsthegroupingtypeforthemediaquery |
[querysetGroupingType:MPMediaGroupingAlbum]; |
NSArray*albums=[querycollections]; |
for(MPMediaItemCollection*albuminalbums){ |
MPMediaItem*representativeItem=[albumrepresentativeItem]; |
NSString*artistName= |
[representativeItemvalueForProperty:MPMediaItemPropertyArtist]; |
NSString*albumName= |
[representativeItemvalueForProperty:MPMediaItemPropertyAlbumTitle]; |
NSLog(@"%@by%@",albumName,artistName); |
NSArray*songs=[albumitems]; |
for(MPMediaItem*songinsongs){ |
NSString*songTitle= |
[songvalueForProperty:MPMediaItemPropertyTitle]; |
NSLog(@"\t\t%@",songTitle); |
} |
} |
collectionsproperty
isanarrayofarrays.Theouterforloopiteratesoverthealbumsperformedthespecifiedartist.Theinnerforloopiteratesoverthesongsinthecurrentalbum.
The
classMPMediaQuery
includesseveralconvenienceconstructorsforcreatingqueriesthatarepreconfiguredwithagroupingtype.Thefollowingstatement,forexample,attachesthe“albums”groupingtypetoanewly-allocatedquery:
MPMediaQuery*query=[MPMediaQueryalbumsQuery]; |
ClassReference.
UsingMediaItemArtwork
Oneofthemostusefulandhigh-impactpropertiesofamediaitemisitsartwork.Todisplayartwork,youuseInterfaceBuilderaswellasXcode.Thestepsareasfollows:Adda
objectUIImageView
toyourviewlayoutinInterfaceBuilder.
AddanIBOutletinstancevariabletoyourviewcontrollerclasstoconnecttothe
UIImageViewobject.
Retrievetheartworkfromthemediaitemthatownsit(havingpreviouslyretrievedthemediaitemasdescribedinthischapter).
Converttheartworktoa
object,UIImage
thenassignittoyourlayout’s
UIImageViewobject.
Listing4-7showshowtodosteps3and4.
Listing4-7Displayingalbumartworkforamediaitem
MPMediaItemArtwork*artwork= |
[mediaItemvalueForProperty:MPMediaItemPropertyArtwork]; |
UIImage*artworkImage= |
[artworkimageWithSize:albumImageView.bounds.size]; |
if(artworkImage){ |
albumImageView.image=artworkImage; |
}else{ |
albumImageView.image=[UIImageimageNamed:@"noArtwork.png"]; |
} |
noArtwork.pngfileusedinthelastlineofListing
4-7isafallbackimagethatyouaddtoyourXcodeproject,forusewhenamediaitemhasnoassociatedartwork.
相关文章推荐
- Android开发之内存管理
- 开源项目 FDTemplateLayoutCell研究
- pow(x,n)
- JdbcTemplate使用别名绑定变量
- 大型分布式网站架构
- 死刑犯和CEO写给母亲的信,价值上亿!惊醒无数父母!
- linux访问windows共享文件夹的两种方法
- Leetcode Minimum Height Trees
- 取消tableviewcell选中效果
- 10位世界级投资大师100金句
- MySQL中TPS和QPS的计算方式
- 解决 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) 问题
- Charles抓包使用教程
- css行级行内元素横向居中
- 寒假集训四之判断长方形问题 hdu5258 暴力枚举
- iOS中使用AVPLayer自定义视频播放器
- Android实现3D页面加载进度条动画
- ASP.NET应用程序与页面生命周期
- OnClick事件的Sender参数的前世今生——TWinControl.WinProc优先捕捉到鼠标消息,然后使用IsControlMouseMsg函数进行消息转发给图形子控件(意外发现OnClick是由WM_LBUTTONUP触发的)
- 分析cocos2d-x在Android上的编译过程(1):cocco2d-x是怎样生成的Android的文件夹结构