1
votes

In collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath method i m trying to load array of audio files into collection view cells but based on indexPath row it is skipping cell at index 0 and from cell at index 1 it is playing audio file when cell selected. i m unable to understand why.

Here is my code

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
audioArray =[[NSArray alloc] initWithObjects:@"0", @"1", @"2", @"3", nil];

NSString *filePath = [audioArray objectAtIndex:indexPath.row];

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:fileURL error:nil];

}

If some one can point me in the right direction. I will appreciate.

Thanks for help.

1

1 Answers

3
votes

Finally fixed it

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

if ([[segue identifier] isEqualToString:@"showDetail"])
{
    NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];

    // load the image, prevent it from being cached using 'initWithContentsOfFile'

    NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", selectedIndexPath.item];

    NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"jpg"];

    UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];


    NSString *audioToLoad = [NSString stringWithFormat:@"%d", selectedIndexPath.item];


    NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:audioToLoad ofType: @"mp3"];

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

    audioPlayer = [[AVAudioPlayer alloc]
                   initWithContentsOfURL:fileURL error:nil];

    DetailViewController *detailViewController = [segue destinationViewController];

    detailViewController.image = image;

    detailViewController.audioPlayer = audioPlayer;

               }        
            }

It might help some one.