swipeGestureRecognizer not working when restarting app in Ios Simulator - ios-simulator

Im toying around with SwipeGestureRecognizer.
It´s working as I expect, but when I exit the app in the simulator and run it again, the SwipeGestureRecognizer no longer responds. If i run it again after quitting iOS simulator, it works.
This is what I have tried:
#import <UIKit/UIKit.h>
#interface swipeTestUI : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)mangeSwipeControl:(UIGestureRecognizer*)sender;
#end
Implementation file:
#import "swipeTestUI.h"
#interface swipeTestUI ()
#end
#implementation swipeTestUI
#synthesize imageView;
int listOfImages = 0;
- (IBAction)mangeSwipeControl:(UIGestureRecognizer *)sender {
NSLog(#"swipe ok");
NSArray *images=[[NSArray alloc]initWithObjects:
#"1.png",
#"2.png",
#"3.png",
#"4.png",
#"5.png",
#"5.png",nil];
UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];
switch (direction) {
case UISwipeGestureRecognizerDirectionLeft:
listOfImages++;
break;
case UISwipeGestureRecognizerDirectionRight:
listOfImages--;
break;
default:
break;
}
listOfImages = (listOfImages < 0) ? ([images count] -1):listOfImages % [images count];
imageView.image = [UIImage imageNamed:[images objectAtIndex:listOfImages]];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

I think this is an iOS simulator issue. I have modified the code a bit, I think its more effective
the header file is the same, the implementation file is as followed.
-(IBAction)manageSwipeControl:(UISwipeGestureRecognizer *)gesture {
NSArray *images=[[NSArray alloc]initWithObjects:
#"1.png",
#"2.png",
#"3.png",
#"4.png",
#"5.png",
#"6.png",nil];
if (gesture.direction == UISwipeGestureRecognizerDirectionLeft)
{
listOfImages++;
}
else if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
{
listOfImages--;
}
listOfImages = (listOfImages < 0) ? ([images count] -1):listOfImages % [images count];
imageView.image = [UIImage imageNamed:[images objectAtIndex:listOfImages]];
//[self.imageView removeGestureRecognizer:sender];
}
Works like a charm. Funny thing. When I quit the application in the iOS simulator, and reopen it. It still works. If I quit and remove it from iOS simulator memory - it does not. If I launch the iOS simulator directly from the OS, no problem what so ever. I can both quit and remove it from memory, and it still works.
Still, a fun way to spend on a rainy weekend. Hope this info is useful to other new developers like myself.

Related

Saving an ALAsset to SQLite3 database - retrieve error

I'm trying to save a list of assets to upload in a sqllite3 db, but when i parse the database and set the assets to an array, then try to use the asset i get a SIGABRT error.
ALAsset *asset = (ALAsset *) assets[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"image%d: ready to upload.",indexPath.row];
cell.detailTextLabel.text = #"1.3MB to folder <server folder>";
[[cell imageView] setImage:[UIImage imageWithCGImage:[asset thumbnail]]];// SIGABRT ERROR
Im saving the ALAsset to the database as a string (TEXT) with UTF8formatting
NSMutableArray *tmpArray = [NSMutableArray alloc]init];
///get sql
[tmpArray addObject:someStringFromSQL];
///end sql loop
assets = [tmpArray mutableCopy];
in the code above I tried:
[[cell imageView] setImage:[UIImage imageWithCGImage:[(ALAsset *) asset thumbnail]]];// SIGABRT ERROR
and that didn't work.
This is the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString thumbnail]: unrecognized selector sent to instance 0xc0a7800'
Any suggestions?
Also as a side question: Does anyone know how to get the file size (i.e. 1.3MB) from the asset?
BLOCK:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//do stuff in cell
NSURL *aURL =[NSURL URLWithString:[assets objectAtIndex:indexPath.row]];
[assetsLibrary assetForURL:aURL resultBlock:^(ALAsset *asset){
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithCGImage:[asset thumbnail]];
});
[[NSNotificationCenter defaultCenter] postNotificationName:#"newAssetImageRetrieved" object:nil];
//in this notificaton I'm reloading the data; its putting the tableview in an infinite loop - but the images display...
}
failureBlock:^(NSError *error){
// error handling
NSLog(#"Can't get to assets: FAILED!");
}];
//cell.imageView.image = [UIImage imageWithCGImage:[asset thumbnail]];
cell.textLabel.text = [NSString stringWithFormat:#"image%d: ready to upload.",indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"1.3MB to folder %#", [destinations objectAtIndex:indexPath.row]];
//[[cell imageView] setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
return cell;
}
There are a couple of issues with your code sample:
The image retrieval is happening asynchronously, so when you try to update the image, you want to make sure the cell is still visible (and not reused for another NSIndexPath).
In this case, the retrieval from the ALAssetsLibrary will probably be so fast that this isn't critical, but it's a good pattern to familiarize yourself with, because if you're ever retrieving images over the Internet, this issue becomes increasingly important.
Because cells are being reused, if you don't find the image immediately and have to update it asynchronously, make sure you reset the UIImageView before initiating the asynchronous process. Otherwise, you'll see a "flickering" of replacing old images with new ones.
You are using UITableViewCell for your cell. The problem with that is that it will layout the cell based upon the size of the image present by the time cellForRowAtIndexPath finishes.
There are two easy solutions to this. First, you could initialize the cell's imageView to be a placeholder image of the correct size. (I usually have an image called placeholder.png that is all white or all transparent that I add to my project, which is what I used below.) This will ensure that cell will be laid out properly, so that when you asynchronously set the image later, the cell will be laid out properly already.
Second, you could alternatively use a custom cell whose layout is fixed in advance, bypassing this annoyance with the standard UITableViewCell, whose layout is contingent upon the initial image used.
I'd suggest using a NSCache to hold the thumbnails images. That will save you from having to constantly re-retrieve the thumbnail images as you get them from your ALAssetsLibrary as you scroll back and forth. Unfortunately, iOS 7 broke some of the wonderful NSCache memory-pressure logic, so I'd suggest a cache that will respond to memory pressure and purge itself if necessary.
Anyway, putting that all together, you get something like:
#interface ViewController ()
#property (nonatomic, strong) NSMutableArray *assetGroups;
#property (nonatomic, strong) ALAssetsLibrary *library;
#property (nonatomic, strong) ThumbnailCache *imageCache;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageCache = [[ThumbnailCache alloc] init];
self.assetGroups = [NSMutableArray array];
self.library = [[ALAssetsLibrary alloc] init];
[self.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (!group) {
[self.tableView reloadData];
return;
}
CustomAssetGroup *assetGroup = [[CustomAssetGroup alloc] init];
assetGroup.name = [group valueForProperty:ALAssetsGroupPropertyName];
assetGroup.assetURLs = [NSMutableArray array];
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
[assetGroup.assetURLs addObject:[result valueForProperty:ALAssetPropertyAssetURL]];
}
}];
[self.assetGroups addObject:assetGroup];
} failureBlock:^(NSError *error) {
NSLog(#"%s: enumerateGroupsWithTypes error: %#", __PRETTY_FUNCTION__, error);
}];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.assetGroups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
CustomAssetGroup *group = self.assetGroups[section];
return [group.assetURLs count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
CustomAssetGroup *group = self.assetGroups[section];
return group.name;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// note, these following three lines are unnecessary if you use cell prototype in Interface Builder
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
CustomAssetGroup *group = self.assetGroups[indexPath.section];
NSURL *url = group.assetURLs[indexPath.row];
NSString *key = [url absoluteString];
UIImage *image = [self.imageCache objectForKey:key];
if (image) {
cell.imageView.image = image;
} else {
UIImage *placeholderImage = [UIImage imageNamed:#"placeholder.png"];
cell.imageView.image = placeholderImage; // initialize this to a placeholder image of the right size
[self.library assetForURL:url resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:asset.thumbnail]; // note, use thumbnail, not fullResolutionImage or anything like that
[self.imageCache setObject:image forKey:key];
// see if the cell is still visible, and if so, update it
// note, do _not_ use `cell` when updating the cell image, but rather `updateCell` as shown below
UITableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath]; // not to be confused with similarly named table view controller method ... this one checks to see if cell is still visible
if (updateCell) {
[UIView transitionWithView:updateCell.imageView duration:0.1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
updateCell.imageView.image = image;
updateCell.textLabel.text = asset.defaultRepresentation.filename;
} completion:nil];
}
} failureBlock:^(NSError *error) {
NSLog(#"%s: assetForURL error: %#", __PRETTY_FUNCTION__, error);
}];
}
return cell;
}
#end
The above uses the following classes:
/** Thumbnail cache
*
* This cache optimizes retrieval of old thumbnails. This purges itself
* upon memory pressure and sets a default countLimit.
*/
#interface ThumbnailCache : NSCache
// nothing needed here
#end
#implementation ThumbnailCache
/** Initialize cell
*
* Add observer for UIApplicationDidReceiveMemoryWarningNotification, so it purges itself under memory pressure
*/
- (instancetype)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
self.countLimit = 50;
};
return self;
}
/** Dealloc
*
* Remove observer before removing cache
*/
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
#end
and
/** Custom AssetGroup object
*
* This is my model object for keeping track of the name of the group and list of asset URLs.
*/
#interface CustomAssetGroup : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, strong) NSMutableArray *assetURLs;
#end
#implementation CustomAssetGroup
// nothing needed here
#end
You have to explore all the code base related to the save and retrieve functionality.
However, here are some good tips.
Save the ALAsset Url instead of saving the entire ALAsset as a string.
Retrieve the ALAsset Url from the database and convert it to NSUrlString.
Use ALAsset Library to load the image or thumbnail back.
Hope this will help you.

AVAudioPlayer sounds garbled on iPhone without headphones

I have 23 music files (10-20 seconds in length) that I want to play when the user selects them and presses the play button. It works find on my iPad and on the simulators, with or without earphones. But on the iPhone device without earphones, around 80% of the files sound garbled, the volume is low, and some are barely legible. I can plug the earphones in, and they sound fine. As soon as I unplug the earphones, the sounds are garbled again.
Since some of the files always play fine, I converted all the original mp3's that I was using into the AAC format with a sample rate of 44100. But the same files play fine, while most are distorted when playing on the iphone device.
I've tried several settings for AVAudioSession category: playback, playAndRecord, ambient. I've tried storing the files in core data and using initWithData instead of initWithContentsOfURL. Can anyone suggest what else I might try? Or how I might get clues into why I'm having this problem?
Here is my code. There are 3 relevant files. The ViewController that has a button to play a selected music file, an AVPlaybackSoundController that has all the audio logic, and a Singleton that has an array with the filenames.
My ViewController creates an AVPlaybackSoundController through the Nib.
IBOutlet AVPlaybackSoundController *avPlaybackSoundController;
#property (nonatomic, retain) AVPlaybackSoundController *avPlaybackSoundController;
- (IBAction) playButtonPressed:(id)the_sender
{
self.currentRhythmSampleIndex = arc4random() % [[CommonData sharedInstance].rhythmSampleArray count];
[self.avPlaybackSoundController playMusic:self.currentRhythmSampleIndex];
self.playBtn.hidden=YES;
self.pauseBtn.hidden=NO;
}
AVPlaybackSoundController.m
- (void) awakeFromNib
{
[self initAudioSession:AVAudioSessionCategoryPlayback];
[self initMusicPlayer];
}
- (void) initAudioSession:(NSString *const)audioSessionCategory
{
NSError* audio_session_error = nil;
BOOL is_success = YES;
is_success = [[AVAudioSession sharedInstance] setCategory:audioSessionCategory error:&audio_session_error];
if(!is_success || audio_session_error){
NSLog(#"Error setting Audio Session category: %#", [audio_session_error localizedDescription]);
}
[[AVAudioSession sharedInstance] setDelegate:self];
audio_session_error = nil;
is_success = [[AVAudioSession sharedInstance] setActive:YES error:&audio_session_error];
if(!is_success || audio_session_error){
NSLog(#"Error setting Audio Session active: %#", [audio_session_error
localizedDescription]);
}
}
- (void) initMusicPlayer
{
NSError* file_error = nil;
NSURL* file_url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"musicFile1" ofType:#"m4a"]
isDirectory:NO];
avMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file_url
error:&file_error];
if(!file_url || file_error){
NSLog(#"Error loading music file: %#", [file_error
localizedDescription]);
}
self.avMusicPlayer.delegate = self;
self.avMusicPlayer.numberOfLoops = 0xFF;
[file_url release];
}
-(void) playMusic:(NSUInteger)rhythmSampleIdx
{
CommonData *glob = [CommonData sharedInstance];
if (rhythmSampleIdx > [glob.rhythmSampleArray count])
return; // bug if we hit here
// if we were already playing it, just resume
if ((self.avMusicPlayer) && (rhythmSampleIdx == self.currentRhythmSampleIndex)){
[self.avMusicPlayer play];
}
else{ // re-init player with new rhythm
if (self.avMusicPlayer){
[self.avMusicPlayer stop];
[self.avMusicPlayer setCurrentTime:0.0];
}
NSError* error = nil;
RhythmSample *rhythmSample = [glob.rhythmSampleArray objectAtIndex:rhythmSampleIdx];
NSString* rhythm_filename = [self getRhythmFileName:rhythmSampleIdx];
NSURL* file_url = [[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle]
pathForResource:rhythm_filename ofType:#"m4a"] isDirectory:NO]autorelease];
self.avMusicPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:file_url error:&error]autorelease];
[self.avMusicPlayer prepareToPlay]; // shouldn't be needed since we are playing immediately
if(error){
NSLog(#"Error loading music file: %#", [error localizedDescription]);
}else{
self.avMusicPlayer.delegate = self;
self.avMusicPlayer.numberOfLoops = 0xFF; // repeat infinitely
self.currentRhythmSampleIndex = rhythmSampleIdx;
[self.avMusicPlayer play];
}
}
}
I finally decided to obtain the sound files from a different source. The new sound files play fine. I still have no theory as to why the old sound files would play with earphones, but not without them. I really dislike finding solutions without understanding why they work.

Simulator does not show button text

I'm learning to build iPhone apps with XCode 4.5.2 and I noticed something strange. As you can see at the address http://i.stack.imgur.com/purI8.jpg the text inside one of the buttons is not displayed in the iOS6 simulator. I also tried to move the Enter button in the same line of 0 and -, but the text in all three buttons of the line disappeared. Anyone knows what's the cause of this problem and how to solve it? Here is the code:
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation CalculatorViewController
#synthesize display;
#synthesize userIsInTheMiddleOfEnteringANumber;
#synthesize brain = _brain;
- (CalculatorBrain *)brain
{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [self.display.text stringByAppendingString:digit];
} else {
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
- (IBAction)enterPressed
{
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber = NO;
}
- (IBAction)operationPressed:(UIButton *)sender
{
if (self.userIsInTheMiddleOfEnteringANumber) [self enterPressed];
NSString *operation = [sender currentTitle];
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:#"%g", result];
}
#end
According to https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/doc/uid/TP40006815-CH3-SW7
- (void)setTitle:(NSString *)title forState:(UIControlState)state
To set your button titles.
So in your case:
- (IBAction)operationPressed:(UIButton *)sender{
....
[sender setTitle:[NSString stringWithFormat:#"%g", result] forState: UIControlStateNormal];
// lets assume you want the down states as well:
[sender setTitle:[NSString stringWithFormat:#"%g", result] forState: UIControlStateSelected];
[sender setTitle:[NSString stringWithFormat:#"%g", result] forState: UIControlStateHighlighted];
}

Thread 1:EXC_BAD_ACCESS(code=2, address=0xbf7ffffc)

Am writing a simple multi view application with one root controller and two view controllers (blue and yellow). When I try to run it in the iPhone Simulator, I get an error by the #synthesize property. I have commented out the error on that line.
Can you tell me what the error means, and how can I get the app to run?
Thank you.
#import "SwitchViewController.h"
#import "BlueViewController.h"
#import "YellowViewController.h"
#interface SwitchViewController ()
#end
#implementation SwitchViewController
#synthesize yellowViewController;
#synthesize blueViewController; //Thread 1:EXC_BAD_ACCESS(code=2, address=0xbf7ffffc)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)loadView
{
// If you create your views manually, you MUST override this method and use it to create your views.
// If you use Interface Builder to create your views, then you must NOT override this method.
}
- (void)viewDidLoad
{
self.blueViewController = [[BlueViewController alloc]initWithNibName:#"BlueView" bundle:nil];
[self.view insertSubview:self.blueViewController.view atIndex:0];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)switchViews:(id)sender
{
if(self.yellowViewController.view.superview==nil) {
if(self.yellowViewController==nil) {
self.yellowViewController =
[[YellowViewController alloc] initWithNibName:#"YellowView" bundle:nil];
}
[blueViewController.view removeFromSuperview];
[self.view insertSubview:self.yellowViewController.view atIndex:0];
} else {
if (self.blueViewController == nil) {
self.blueViewController =
[[BlueViewController alloc] initWithNibName:#"BlueView" bundle:nil];
}
}
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use
if (self.blueViewController.view.superview == nil) {
self.blueViewController = nil;
} else {
self.yellowViewController = nil;
}
}
#end
Comment out the loadView method in your SwitchViewController, BlueViewController, and YellowViewController. The empty application template was changed to leave these uncommented in recent versions of XCode, but the Beginning iOS Development book you are following used an older version with the stubbed methods pre-commented.

AVAudioPlayer Notification issue

So I'm almost done with my app and I've hit a wall and cannot get around this final problem.
I basically have 2 view's. A main page and the game play screen.
On the first play the game works fine, but when i leave the main screen and then return to the game screen all the sounds are duplicating and firing the the playerItemDidReachEnd early (because I'm guessing there are 2 instances of it, but it cannot seem to get the player to stop this. Here is the basic code causing this. Any help would go a long way, thanks. I'm not sure if my issue is i'm creating multiple instances of View2 in View1 or if I'm creating multiple player objects in view2 thus duplicating the notification.
I know there is a lot going on in my - (void)playerItemDidReachEnd:(NSNotification *)notification, but it works fine on the first load of the page, its only when I click "go back to view1" and then go back in to View2 that the issue happens.
View1ViewController.h
----------------------
#import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h>
#import "ApplicationViewController.h"
#interface MonsterSpellViewController : UIViewController {
}
-(IBAction)showView1;
View2ViewController.m
----------------------
-(IBAction)showView2{
ApplicationViewController *view2 = [[ApplicationViewController alloc]initWithNibName:#"ApplicationViewController" bundle:nil];
view2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:view2 animated:YES];
}
View2ViewController.h
------------------------
#import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h>
#import "(i know here are arrows here, but can't make them show)AVFoundation/AVFoundation.h>
#class AVAudioPlayer;
#interface ApplicationViewController : UIViewController{
AVAudioPlayer *avPlayer;
}
View2ViewController.m
-------------------------
#import "View2ViewController.h"
#synthesize avPlayer;
-(AVAudioPlayer *)avPlayer {
if(!avPlayer) avPlayer = [[AVAudioPlayer alloc]init];
return avPlayer;
}
-(void) viewDidLoad
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:avPlayer];
}
-(IBAction)playSoundTest
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/monster3.mp3", [[NSBundle mainBundle] resourcePath]]];
self.avPlayer = [AVPlayer playerWithURL:url];
[self.avPlayer play];
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
//[player seekToTime:kCMTimeZero];
if (playEscape == YES) {
[self btnEscapeSound];
playEscape = NO;
}
if ((startButton.hidden == NO) && (letterCount != -1) && (playFinal == YES))
{
[self btnFinalSound];
playFinal = NO;
playEscape = YES;
}
NSLog(#"Player Check accessed");
if (letterCount == 3) {
if (Winner == letterCount) {
//moveNextSound = YES;
if (intLoopCount < 104)
{
if (intLoopCount<104) {
[self btnStartOver:intLoopCount];
playFinal = NO;
//intLoopCount++;
}
if (intLoopCount==104) {
startButton.hidden=NO;
playFinal = YES;
}
}
}
}
if (letterCount == 4) {
if (Winner == letterCount) {
//moveNextSound = YES;
if (intLoopCount < 105)
{
[self btnStartOver:intLoopCount];
//intLoopCount++;
if (intLoopCount==105) {
startButton.hidden=NO;
playFinal = YES;
}
}
}
}
}
}
-(IBAction)goBack:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
Try adding [view2 release]; after [self presentModalViewController:view2 animated:YES];

Resources