Load audiofile array to collection view cells in sequence manner - iphone

I have loaded images and labels to custom collectionview cells in this method
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
Giving the cells title based on actual NSIndexPath value in the same method
cell.label.text = [NSString stringWithFormat:#"{%ld,%ld}", (long)indexPath.row, (long)indexPath.section];
Loading different images in each cell of the custom collection view cells in the same method
NSString *imageToLoad = [NSString stringWithFormat:#"%d.jpg", indexPath.row];
cell.image.image = [UIImage imageNamed:imageToLoad];
I want to load different audio files in each cell of the custom collection view cells in the same method
audioArray =[[NSArray alloc] initWithObjects:#"Theme1", #"Theme2", #"Theme3", #"Theme4", nil];
NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
If i add indexPath.row below
NSString *filePath = [audioArray objectAtIndex:indexPath.row];
Then it always plays "Theme4" last audio file from within the array in all cells
And if i write 0
NSString *filePath = [audioArray objectAtIndex:0];
Then it plays always "Theme1" the very first audio file in all cells
How i can load different audio files in each cell of the custom collection view cells.
Thanks for help.

You should add these lines of code in
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
audioArray =[[NSArray alloc] initWithObjects:#"Theme1", #"Theme2", #"Theme3", #"Theme4", 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];
}
rather than in
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
Hope this helps.

Related

How to PrepareforSegue for multiple objects : UIImageView and audiofile

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"])
{
NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];
// load the image, to prevent it from being cached we use 'initWithContentsOfFile'
NSString *imageNameToLoad = [NSString stringWithFormat:#"%d_full", selectedIndexPath.row];
NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:#"jpg"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];
DetailViewController *detailViewController = [segue destinationViewController];
detailViewController.image = image;
}
}
How can i add audio file in prepareforSegue along with UIImageview for destinationViewController
audioArray =[[NSArray alloc] initWithObjects:#"Theme1", #"Theme2", #"Theme3", #"Theme4", nil];
NSString *filePath = [audioArray objectAtIndex:0];
NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
Thanks

Display JSON data in UITableView

My app is loading some data thought JSON and everything is working fine, but when I try to display those data in my UITableView cell, nothing happens. My code is below:
Get Data(JSON):
-(void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"];
testeDictionary = [latestLoans objectAtIndex:0];
testeLabel.text = [NSString stringWithFormat:#"%#",[testeDictionary objectForKey:#"id"]];
testeString = [testeDictionary objectForKey:#"username"];
[miArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:testeString,#"username",nil]];
}
UITableView :
-(UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = (UITableViewCell *)[self.settingsTableView dequeueReusableCellWithIdentifier:#"CellD"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CellD" owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
}
if ([indexPath row] == 0) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CellA" owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
NSDictionary *itemAtIndex = (NSDictionary *)[miArray objectAtIndex:indexPath.row];
UILabel *usernameString = (UILabel *)[cell viewWithTag:1];
usernameString.text = [itemAtIndex objectForKey:#"id"]; <== MUST DISPLAY JSON VALUE
}
return cell;
}
More clearly I need to display this [testeDictionary objectForKey:#"id"] on the usernameString.text?
You are not storing the id
[miArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:testeString,#"username",nil]];
I suppose what you want to be doing is something like this
NSString *idString = [NSString stringWithFormat:#"%#", [testeDictionary objectForKey:#"id"]];
[miArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
testeString, #"username",
idString, #"id",
nil]];
EDIT (explanation)
In your method fetchedData: you extract the id and set the text of some label to the id.
testeLabel.text = [NSString stringWithFormat:#"%#",[testeDictionary objectForKey:#"id"]];
After that you forget about the id. You then proceed to extract the username and you create a dictionary containing only the username and add that dictionary to an array called miArray.
[miArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:testeString,#"username",nil]];
Notice that you do not specify any key named "id".
Later, you fetch a dictionary from miArray. This dictionary is the one you created with only one key, i.e. "username". You tell it to get an object for the key "id", but since you never specified that key, you get a nil value.
Bottom line, try my solution.

contentsOfDirectoryAtPath crashes

I want to list files in the directory in table view of navigation control.
It shows files in the directory.
But whenever I scroll down, my simulator crashes. What is the problem?
dirArray is defined in .h file as NSArray *dirArray.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSFileManager defaultManager]currentDirectoryPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
return [dirArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
NSString *fileName = [dirArray objectAtIndex:indexPath.row];
cell.textLabel.text = fileName;
return cell;
}
Your problem is that
dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];
will have dirArray pointing to an autoreleased object. So by the time you are accessing it later, it is being deallocated. Either retain it.
dirArray = [[fileManager contentsOfDirectoryAtPath:path error:nil] retain];
Or much better, declare it as a property and do
self.dirArray = [fileManager contentsOfDirectoryAtPath:path error:nil];
you should make property of the your array and #synthesize it.
or
you shold alloc array and relese it in the dealloc.

Saving data to a plist file

I am having a little trouble saving to a plist file, when i am reading the data i am using:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return amounts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Create Cell
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cell"];
//Fill cell
NSDictionary *budgetItem = [amounts objectAtIndex:indexPath.row];
cell.textLabel.text = [budgetItem objectForKey:#"value"];
cell.detailTextLabel.text = [budgetItem objectForKey:#"description"];
//Return it
return cell;
}
- (void) loadData{
// Load items
NSString *error;
NSPropertyListFormat format;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:#"savebudget" ofType:#"plist"];
NSData *plistData = [NSData dataWithContentsOfFile:localizedPath];
NSArray *amountData = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if (amountData) {
self.amounts = [[NSMutableArray alloc] initWithCapacity:[amountData count]];
for (NSDictionary *amountsDictionary in amountData) {
[self.amounts addObject:amountsDictionary];
}
}
Which works fine from a static plist file with-in my resources folder, but when i try and create my own, nothing seems to happen:
-(void) addData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"saveBudget" ofType:#"plist"];
NSMutableDictionary* plist = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[plist setValue:amountTxt.text forKey:#"value"];
[plist writeToFile:path atomically:YES];
[plist release];
}
- (IBAction)add:(id)sender {
[self addData];
[self.delegate budgetEnterMinusViewControllerDidFinish:self];
}
Any help more than welcome...
Ugh. Terrible and confusing code. First: use this to load instead:
NSString* path = [[NSBundle mainBundle] pathForResource:#"savebudget" ofType:#"plist"];
NSDictionary* amountData = [NSDictionary dictionaryWithContentsOfFile: path error: NULL];
if (amountData) {
self.amounts = [NSMutableArray arrayWithArray: amountData];
}
Note, no retain or alloc/init here because you are assigning to a retaining property.
So the real problem:
You are reading a plist that that you say contains an array of dictionaries. But then when you add data, you try to write back one single dictionary to that same plist.
Also, in your addData method you do not actually add any data.
And ... If you load your initial data from your app's bundle, then you should write it back to your ~/Documents directory after changing it. And of course read it back from there the next time your app starts.

Json Parser output display in tableview

I am trying to parse using JSON Parser and the result which i get i have to put it into table view. I've passed a constant key value and a string .
Is there parsing steps wrong? or missed.
I have included the code for the JSON parser.
Thanks in advance.
SBJSON *parser = [[SBJSON alloc] init];
NSString *urlString =[NSString stringWithFormat:#"http://api.shopwiki.com/api/search?key=%#&q=%#",apiKey, string];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSMutableArray *statuses = [[NSMutableArray alloc]init];
statuses = [parser objectWithString:json_string error:nil];
NSLog(#"Array Contents: %#", statuses);
NSMutableArray *statuses0 = [[NSMutableArray alloc]init];
statuses0 = [statuses valueForKey:#"offers"];
NSLog(#"Array Contents: %#", statuses0);
//For Title
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
statuses1 = [[[statuses valueForKey:#"offers"] valueForKey:#"offer"]valueForKey:#"title"];
NSLog(#"Array Contents 4 Title: %#", statuses1);
Here in statuses1 array i get 20 objects which are all titles, now i just want to display that titles into tableview:-
snippet code for tableview:-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"status count:%d",[statuses1 count]);
return [statuses1 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Inside Tableview");
int counter=indexPath.row;
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",counter];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
NSLog(#"Inside Tableview 1");
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
NSLog(#"Inside Tableview 2");
return cell;
}
I get Bad excess exception whten it hits on :-
cell.textLabel.text=[statuses1 objectAtIndex:indexPath.row];
Please give me the solution
thanks in advance:-
If you're getting EXC_BAD_ACCESS on that line, it's probably because statuses1 has been released by the time cellForRowAtIndexPath is called. What block of code is this line in?
NSMutableArray *statuses1 = [[NSMutableArray alloc]init];
The statuses1 variable above is local to whatever scope you've declared it in. Do you then assign it to your UITableViewController.statuses1 ivar? Is that a retained property?