Reputation: 5
I am using the following code to try to get the trackName from iTunes API. It should come from this link for example: https://itunes.apple.com/search?term=EMINEM&entity=song&limit=3 It keeps returning nothing (label is blank and it is not because the label is too small)
- (void)pressSearchKey {
NSInteger numberOfResults = 3;
NSString *searchString = self.keyboard.textField.text;
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?term=%@&entity=song&limit=%ld",searchString,numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:@"results"];
NSArray *arrayTracks;
for (NSDictionary *bpDictionary in array) {
arrayTracks = [bpDictionary objectForKey:@"trackName"];
}
dispatch_async(dispatch_get_main_queue(), ^{
self.keyboard.firstLabel.text = [arrayTracks objectAtIndex:1];
});
}
});
}
Upvotes: 0
Views: 371
Reputation: 72825
You've got a couple of problems in this one too.
encodedSearchString
when building finalSearchString
Fixed:
NSInteger numberOfResults = 3;
NSString *searchString = @"EMINEM";
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:@"https://itunes.apple.com/search?term=%@&entity=song&limit=%ld",encodedSearchString,numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:@"results"];
NSArray *arrayTracks;
for (NSDictionary *bpDictionary in array) {
arrayTracks = [bpDictionary objectForKey:@"trackName"];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@", [arrayTracks objectAtIndex:1]);
});
}
});
Upvotes: 0