Playlist Generator  1.0
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Properties Defines
Playlist2/DisplayPlaylistViewController.m
Go to the documentation of this file.
00001 //
00002 //  DisplayPlaylistViewController.m
00003 //  Playlist2
00004 //
00005 //  Created by Max Woolf on 15/12/2011.
00006 //  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
00007 //
00008 
00009 #import "DisplayPlaylistViewController.h"
00010 #import "SpotifyURILookup.h"
00011 #import "ExtractSpotifyURI.h"
00012 #import "URIToURLConverter.h"
00013 #import "SpotifyPlayer.h"
00014 #import "SBJson.h"
00015 
00016 @implementation DisplayPlaylistViewController
00017 
00018 -(id)initWithArtistArray:(NSArray *)artists tracksArray:(NSArray *)tracks
00019 {
00020     artistList = artists;
00021     trackList = tracks;
00022     self = [super init];
00023     return self;
00024 }
00025 
00026 - (void)didReceiveMemoryWarning
00027 {
00028     // Releases the view if it doesn't have a superview.
00029     [super didReceiveMemoryWarning];
00030     
00031     // Release any cached data, images, etc that aren't in use.
00032 }
00033 
00034 #pragma mark - Table View Methods
00035 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
00036 {
00037     return 1;
00038 }
00039 
00040 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
00041 {
00042     if([artistList count] == [trackList count])
00043     {
00044         return [artistList count];
00045     }
00046     return 0;
00047 }
00048 
00049 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
00050     static NSString *MyIdentifier = @"MyIdentifier";
00051     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
00052     if (cell == nil) {
00053         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier];
00054         [cell.textLabel setText:[trackList objectAtIndex:indexPath.row]];
00055         [cell.detailTextLabel setText:[artistList objectAtIndex:indexPath.row]];
00056         //[cell setAccessoryView:[activityIndicators objectAtIndex: indexPath.row]];
00057         //[[activityIndicators objectAtIndex:indexPath.row] startAnimating];
00058         [cell setAccessoryType:UITableViewCellAccessoryNone];
00059         [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
00060     }
00061     if([URLs count] > 0){
00062         if([[URLs objectAtIndex:indexPath.row]isEqualToString:@""]){
00063             [cell setAccessoryType: UITableViewCellAccessoryNone];
00064         }else{
00065             [cell setAccessoryType: UITableViewCellAccessoryCheckmark];
00066         }
00067     }
00068     [cells addObject:cell];
00069     return cell;
00070 }
00071 
00072 #pragma mark - Connection Delegate
00073 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
00074 {
00075     NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
00076     int code = [httpResponse statusCode];
00077     
00078     if(code == 400 || code == 403 || code == 404 || code == 406 || code == 500 || code == 503)
00079     {
00080         //Shit's gone doooown. Move on to the next track now!
00081         NSLog(@"%i", code);
00082     }else if(code == 200){
00083         //Everything's hunky dorky.
00084         [receivedData setLength:0];
00085     }else{
00086         //Unknown error.
00087         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"The Spotify metadata API returned an unknown error. There's not much we can do... try again later"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
00088         [alert show];
00089     }
00090     
00091 }
00092 
00093 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
00094 {
00095     [receivedData appendData:data];
00096 }
00097 
00098 -(BOOL)resultsExistForJSON:(NSString *)jsonString
00099 {
00100     SBJsonParser *parser = [[SBJsonParser alloc] init];
00101     NSDictionary *rootDictionary = [parser objectWithString:jsonString];
00102     NSDictionary *info = [rootDictionary valueForKey:@"info"];
00103     NSNumber *numberOfResults = [info valueForKey:@"num_results"];
00104     
00105     NSLog(@"%@", numberOfResults);
00106     if([numberOfResults isEqualToNumber:[NSNumber numberWithInt:0]])
00107     {
00108         return NO;
00109     }
00110     return YES;
00111 }
00112 
00113 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
00114 {
00115     NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
00116     //NSLog(@"%@", receivedString);
00117     //Check if rate limiting kicked in... if it did, we have to wait 10 seconds. 
00118     if([receivedString isEqual:nil])
00119     {
00120         sleep(2);
00121     //If not, check if results were available and add it to the array
00122     }else if([self resultsExistForJSON:receivedString])
00123     {
00124         ExtractSpotifyURI *extractor = [[ExtractSpotifyURI alloc] initWithSpotifyJSONString:receivedString];
00125         [URLs addObject:[extractor getURI]];
00126         [table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:currentConnectionNumber inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
00127     }
00128     
00129     //Chill out for 2 seconds, to stop rate limiting kicking in. (This is annoying.)
00130     //sleep(1);
00131     //When done, increase the connection number, and run the next connection.
00132     
00133     
00134     currentConnectionNumber++;
00135     if(currentConnectionNumber < [connections count])
00136     {
00137         [receivedData setLength:0];
00138         SpotifyURILookup *nextConnection = [connections objectAtIndex:currentConnectionNumber];
00139         [nextConnection start];
00140     }else{
00141         [hud hide:YES];
00142         UIAlertView *spotifyLoginAlert = [[UIAlertView alloc] initWithTitle:@"Login to Spotify" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: @"Login", nil];
00143         [spotifyLoginAlert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
00144         [spotifyLoginAlert show];
00145     }
00146 }
00147 
00148 
00149 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
00150 {
00151     SpotifyPlayer *player = [[SpotifyPlayer alloc]init];
00152     [player setArray:URLs];
00153     [self.navigationController pushViewController:player animated:YES];
00154     
00155     //Login performed... get logging in to spotify!
00156 }
00157 
00158 
00159 #pragma mark - View lifecycle
00160 
00161 -(void)viewDidAppear:(BOOL)animated
00162 {
00163     for(int x = 0; x < [artistList count]; x++)
00164     {
00165         SpotifyURILookup *spotifyJSONConnecton = [[SpotifyURILookup alloc] initWithTrackName:[trackList objectAtIndex:x] artistName:[artistList objectAtIndex:x] delegate:self];
00166         [connections addObject:spotifyJSONConnecton];
00167         //Add each connection to an array and do it one by one. 
00168     }
00169     //Set connection 1 off. 
00170     if(currentConnectionNumber == 0)
00171     {
00172         SpotifyURILookup *currentConnection = [connections objectAtIndex:0];
00173         [currentConnection start];
00174     }
00175 }
00176 
00177 - (void)viewDidLoad
00178 {
00179     //[table becomeFirstResponder];
00180     hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
00181     //[self.view addSubview:hud];
00182     [hud setMode:MBProgressHUDModeIndeterminate];
00183     [hud setLabelText:@"Loading"];
00184     [hud setDetailsLabelText:@"This might take a minute..."];
00185     //[hud show:YES];
00186     receivedData = [[NSMutableData alloc] init];
00187     currentConnectionNumber = 0;
00188     URLs = [[NSMutableArray alloc] initWithCapacity:[artistList count]];
00189     //Create lots of activity indicators so that they are held within the VC
00190     activityIndicators = [[NSMutableArray alloc] init];
00191     for(int x = 0; x < [artistList count]; x++)
00192     {
00193         UIActivityIndicatorView *currentAI = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
00194         [activityIndicators addObject:currentAI];
00195     }
00196     connections = [[NSMutableArray alloc] initWithCapacity:[artistList count]];
00197     [super viewDidLoad];
00198     // Do any additional setup after loading the view from its nib.
00199 }
00200 
00201 - (void)viewDidUnload
00202 {
00203     [super viewDidUnload];
00204     // Release any retained subviews of the main view.
00205     // e.g. self.myOutlet = nil;
00206 }
00207 
00208 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
00209 {
00210     // Return YES for supported orientations
00211     return (interfaceOrientation == UIInterfaceOrientationPortrait);
00212 }
00213 
00214 @end