I need to create a phonegap plugin for ios which fetches all artists from the music library. I know how to do this in Objective C but I have no idea about javascript. I read the phongegap plugin docs for iOS but I dont understand the javascript parts. Please help.
Heres my code…
Artist.m
#import "Artist.h"
#import <MediaPlayer/MediaPlayer.h>
#import <PhoneGap/PGPlugin.h>
@implementation Artist
-(void)getArtistNames:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
MPMediaQuery *query=[MPMediaQuery artistsQuery];
NSArray *artists=[query collections];
artistNames=[[NSMutableArray alloc]init];
for(MPMediaItemCollection *collection in artists)
{
MPMediaItem *item=[collection representativeItem];
[artistNames addObject:[[item valueForProperty:MPMediaItemPropertyArtist]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
uniqueNames=[[NSMutableArray alloc]init];
for(id object in artistNames)
{
if(![uniqueNames containsObject:object])
{
[uniqueNames addObject:object];
}
}
NSLog(@"%@",uniqueNames);
PluginResult *pluginResult=[PluginResult resultWithStatus:PGCommandStatus_OK messageAsArray:uniqueNames];
[self writeJavascript:[pluginResult toSuccessCallbackString:[arguments pop]]];
}
@end
Artist.js
var ArtistPlugin={};
ArtistPlugin.prototype.getArtistNames = function(types, success, fail)
{
return PhoneGap.exec(success, fail, "Artist", "getArtistNames", types);
}
in index.html…
<script type="text/javascript" charset="utf-8" src="Artist.js"></script>
function onDeviceReady()
{
// do your thing!
navigator.notification.alert("PhoneGap is working");
alert('asdasd');
var abc=Artist.getArtistNames(types, success, fail);
alert(abc);
}
A couple things:
It’s best to keep the names the same between your main class in Obj-C and JavaScript. In your case that would mean that either your Obj-C class should be called
ArtistPluginor the JavaScript object you create (and it’s filename) should be calledArtist. I would go with all being calledArtistPlugin. Less likely to clash.The final argument to
PhoneGap.execis an Array, so unlesstypesis an array, it should probably look like:return PhoneGap.exec(success, fail, "Artist", "getArtistNames", [types]);Lastly, make sure you have an entry in the plugins section of your PhoneGap.plist file. The key and value would be the homogenous name you chose from step #1 (i.e.: key: ArtistPlugin, value: ArtistPlugin).
Hope that helps.