您的位置:首页 > 其它

Using the iPod Library

2016-02-22 17:50 393 查看
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/UsingTheiPodLibrary/UsingTheiPodLibrary.html


UsingtheiPodLibrary

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
MPMediaLibrary
class.
Byregisteringtoreceivethesechangenotifications,yourapplicationcanupdateanycacheoflibrarycontentifausersyncstheirdevicewhileyourapplicationisrunning.


RetrievingUngroupedMediaItems

RetrievingmediaitemsfromthedeviceiPodlibrarybeginswithconstructingamediaquery.Thesimplestqueryisthegeneric“
everything

queryshowninListing4-1,whichmatchestheentirecontentsofthelibrary.TheexamplethenlogsthetitlesofthemediaitemstotheXcodedebugger
console,demonstratinguseofthe
items
propertytoinvokethequeryandretrievethemediaitemsitmatches.

Listing4-1Creatingandusingagenericmediaquery

MPMediaQuery*everything=[[MPMediaQueryalloc]init];


NSLog(@"Loggingitemsfromagenericquery...");

NSArray*itemsFromGenericQuery=[everythingitems];

for(MPMediaItem*songinitemsFromGenericQuery){

NSString*songTitle=[songvalueForProperty:MPMediaItemPropertyTitle];

NSLog(@"%@",songTitle);

}

Note:Aswithallcodeexamplesinthisdocument,thisexamplewillruncorrectlyonlyonaprovisionediPhonedevice,notintheSimulator.

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];

Ifyouweretorunthiscode,the
itemsFromArtistQuery
arraywouldcontainonlythoseitemsfromtheiPod
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];

Youconstructeachpredicateusingavalueofyourchoice(suchasanartist’sname)alongwiththeappropriatemediaitempropertykey.ThesekeysaredescribedinMPMediaItem
ClassReferencein
General
MediaItemPropertyKeys
and
Podcast
ItemPropertyKeys
.
Whenyouapplymorethanonepredicatetoaquery,thequerycombinesthemusingthelogicalANDoperator.

Important:Donotapplymorethanonepredicateforaparticularmediaitemproperty.Forexample,donotspecifytwo
MPMediaItemPropertyArtist
predicates
toaquery.Ifyoudo,theresultingbehavioruponusingthequeryisundefined.

Youcanalsoaddpredicatestoaqueryuponinitialization,asshowninListing4-4.(Thetwopredicates
inthisexampleareassumedtobepreviouslydefined.)

Listing4-4Applyingmultiplepredicateswheninitializingamediaquery

NSSet*predicates=

[NSSetsetWithObjects:artistNamePredicate,albumNamePredicate,nil];


MPMediaQuery*specificQuery=

[[MPMediaQueryalloc]initWithFilterPredicates:predicates];

Listing4-4firstdefinesan
NSSet
object
thatcontainstwopredicates,thenallocatesandinitializesamediaqueryusingthe
initWithFilterPredicates:
class
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];

}

InListing4-5,onlyiftheindicatedmediaitempropertykey(inthisexample,
MPMediaItemPropertyGenre
)
canbeusedtoconstructavalidpredicatewillthebodyoftheifstatementexecute.Applerecommendsthatyoualwaysperformachecklikethisbeforeconstructingamediapropertypredicate.


RetrievingMediaItemCollections

Amediaqueryisusefulnotonlyforretrievingungroupedmediaitems.Youcanalsouseamediaquerytoretrievesortedandarrangedcollectionsofmediaitems.Thearrangementyougetdependsonthe
valueyousetforthemediaquery’s
grouping
property.
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);

}

}

YoucanseeinListing4-6thatthevalueofthemediaquery’s
collections
property
isanarrayofarrays.Theouterforloopiteratesoverthealbumsperformedthespecifiedartist.Theinnerforloopiteratesoverthesongsinthecurrentalbum.
The
MPMediaQuery
class
includesseveralconvenienceconstructorsforcreatingqueriesthatarepreconfiguredwithagroupingtype.Thefollowingstatement,forexample,attachesthe“albums”groupingtypetoanewly-allocatedquery:

MPMediaQuery*query=[MPMediaQueryalbumsQuery];

Fordescriptionsofalltheconvenienceconstructors,seeMPMediaQuery
ClassReference.


UsingMediaItemArtwork

Oneofthemostusefulandhigh-impactpropertiesofamediaitemisitsartwork.Todisplayartwork,youuseInterfaceBuilderaswellasXcode.Thestepsareasfollows:

Adda
UIImageView
object
toyourviewlayoutinInterfaceBuilder.

AddanIBOutletinstancevariabletoyourviewcontrollerclasstoconnecttothe
UIImageView
object.

Retrievetheartworkfromthemediaitemthatownsit(havingpreviouslyretrievedthemediaitemasdescribedinthischapter).

Converttheartworktoa
UIImage
object,
thenassignittoyourlayout’s
UIImageView
object.

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"];

}

The
noArtwork.png
fileusedinthelastlineofListing
4-7isafallbackimagethatyouaddtoyourXcodeproject,forusewhenamediaitemhasnoassociatedartwork.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: