Monitor current dB level in Objective-C - objective-c

I'm trying to display the decibel level of incoming sound via the iPhone microphone, everything works in the simulator, but does not work on an actual iOS device. It's like the iPhone is not detecting sound, here is my code:
- (void)viewDidLoad {
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
if (granted) {
[self setup];
NSLog(#"granted");
} else {
NSLog(#"denied");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Microphone Access Denied"
message:#"You must allow microphone access in Settings > Privacy > Microphone"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)setup {
// record audio to /dev/null
NSURL *url = [NSURL fileURLWithPath:#"/dev/null"];
// some settings
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
// create a AVAudioRecorder
NSError *error;
self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
[self.recorder setMeteringEnabled:YES];
if (self.recorder) {
[self.recorder prepareToRecord];
self.recorder.meteringEnabled = YES;
[self.recorder record];
self.levelTimer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector: #selector(levelTimerCallback:) userInfo: nil repeats: YES];
[self.recorder updateMeters];
}
}
- (void)levelTimerCallback:(NSTimer *)timer {
[self.recorder updateMeters];
// here is the DB!
float peakDecebels = [self.recorder peakPowerForChannel:1];
NSLog(#"peak: %f", peakDecebels);
float avaeragePower = [self.recorder averagePowerForChannel:1];
NSLog(#"averagePower: %f", avaeragePower);
[self.dbLabel setText:[NSString stringWithFormat:#"db %f",peakDecebels]];
}

You need to set your audio session appropriately:
NSError* error = nil;
BOOL success = [[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryRecord
error:&error];
if (!success && error) {
NSLog(#"error %#",error);
}
This should be done before you start recording.

Related

How to record video from iPhone camera in iOS 9 objective c?

hello I need to build app that record video from iPhone camera.
I search in the net and not found notting that works in iOS 9.
I get this code from this git project :
https://github.com/versluis/Video-Recorder
This code open camera but not allow Me to take a video.
- (IBAction)recordButton:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
picker.allowsEditing = NO;
NSArray *mediaTypes = [[NSArray alloc]initWithObjects:(NSString *)kUTTypeMovie, nil];
picker.mediaTypes = mediaTypes;
[self presentViewController:picker animated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:#"I'm afraid there's no camera on this device!" delegate:nil cancelButtonTitle:#"Dang!" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (IBAction)playbackButton:(id)sender {
// pick a video from the documents directory
NSURL *video = [self grabFileURL:#"video.mov"];
// create a movie player view controller
MPMoviePlayerViewController * controller = [[MPMoviePlayerViewController alloc]initWithContentURL:video];
[controller.moviePlayer prepareToPlay];
[controller.moviePlayer play];
// and present it
[self presentMoviePlayerViewControllerAnimated:controller];
}
#pragma mark - Delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
// user hit cancel
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// grab our movie URL
NSURL *chosenMovie = [info objectForKey:UIImagePickerControllerMediaURL];
// save it to the documents directory
NSURL *fileURL = [self grabFileURL:#"video.mov"];
NSData *movieData = [NSData dataWithContentsOfURL:chosenMovie];
[movieData writeToURL:fileURL atomically:YES];
// save it to the Camera Roll
UISaveVideoAtPathToSavedPhotosAlbum([chosenMovie path], nil, nil, nil);
// and dismiss the picker
[self dismissViewControllerAnimated:YES completion:nil];
}
- (NSURL*)grabFileURL:(NSString *)fileName {
// find Documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
// append a file name to it
documentsURL = [documentsURL URLByAppendingPathComponent:fileName];
return documentsURL;
}
Ray gave pretty good tutorial about this. Hope it helped.

AVCaptureOutput Delegate

I'm creating an application that is using -(void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection { } function but that function is not being called. To furtherly explain, the application is using code from this tutorial to create a video recording app. When I ran the tutorial's code in xCode it ran the function above but when I copied it over into my application, not modifying it in anyway, it was never called.
Here's the code used:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError *error = nil;
AVCaptureSession *session = [[AVCaptureSession alloc] init];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
[session setSessionPreset:AVCaptureSessionPreset640x480];
} else {
[session setSessionPreset:AVCaptureSessionPresetPhoto];
}
// Select a video device, make an input
AVCaptureDevice *device;
AVCaptureDevicePosition desiredPosition = AVCaptureDevicePositionFront;
// find the front facing camera
for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
if ([d position] == desiredPosition) {
device = d;
isUsingFrontFacingCamera = YES;
break;
}
}
// fall back to the default camera.
if( nil == device )
{
isUsingFrontFacingCamera = NO;
device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
// get the input device
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if( !error ) {
// add the input to the session
if ( [session canAddInput:deviceInput] ){
[session addInput:deviceInput];
}
previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
previewLayer.backgroundColor = [[UIColor blackColor] CGColor];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
CALayer *rootLayer = [previewView layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:[rootLayer bounds]];
[rootLayer addSublayer:previewLayer];
[session startRunning];
}
session = nil;
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:
[NSString stringWithFormat:#"Failed with error %d", (int)[error code]]
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alertView show];
[self teardownAVCapture];
}
NSDictionary *detectorOptions = [[NSDictionary alloc] initWithObjectsAndKeys:CIDetectorAccuracyLow, CIDetectorAccuracy, nil];
faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:detectorOptions];
// Make a video data output
videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
// we want BGRA, both CoreGraphics and OpenGL work well with 'BGRA'
NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject:
[NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
[videoDataOutput setVideoSettings:rgbOutputSettings];
[videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; // discard if the data output queue is blocked
// create a serial dispatch queue used for the sample buffer delegate
// a serial dispatch queue must be used to guarantee that video frames will be delivered in order
// see the header doc for setSampleBufferDelegate:queue: for more information
videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL);
[videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];
if ( [session canAddOutput:videoDataOutput] ){
[session addOutput:videoDataOutput];
}
// get the output for doing face detection.
[[videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:YES];
//[self setupCaptureSession];
}
Okay I think I know what the problem is. You had [session startRunning] even before you set up your videoDataOutput. A session with no video data output....well, will not call the AVCaptureOutput delegate.

Can't play system sounds after capturing audio / video

I'm recoding audio/video using AVfoudnation. and I need to play a sounds, using system sounds, before I start capturing video/audio. This is working correctly the first time, but when I try to do it the second time, the system audi doesn't play. My guess is that something in the AVfoundation is not been released correctly.
In my application deletage, I have this code in the applicationDidFinishLaunching method:
VKRSAppSoundPlayer *aPlayer = [[VKRSAppSoundPlayer alloc] init];
[aPlayer addSoundWithFilename:#"sound1" andExtension:#"caf"];
self.appSoundPlayer = aPlayer;
[aPlayer release];
and also this method
- (void)playSound:(NSString *)sound
{
[appSoundPlayer playSound:sound];
}
As you can see I'm using VKRSAppSoundPlayer, which works great!
In a view, I have this code:
- (void) startSession
{
self.session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
if([session canSetSessionPreset:AVCaptureSessionPreset640x480])
session.sessionPreset = AVCaptureSessionPresetMedium;
[session commitConfiguration];
CALayer *viewLayer = [videoPreviewView layer];
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = viewLayer.bounds;
[viewLayer addSublayer:captureVideoPreviewLayer];
self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCameraIfAvailable] error:nil];
self.audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:nil];
if(videoInput){
self.videoOutput = [[AVCaptureMovieFileOutput alloc] init];
[session addOutput:videoOutput];
//[videoOutput release];
if([session canAddInput:videoInput]){
//[session beginConfiguration];
[session addInput:videoInput];
}
//[videoInput release];
[session removeInput:[self audioInput]];
if([session canAddInput:audioInput]){
[session addInput:audioInput];
}
//[audioInput release];
if([session canAddInput:audioInput])
[session addInput:audioInput];
NSLog(#"startRunning!");
[session startRunning];
[self startRecording];
if(![self recordsVideo])
[self showAlertWithTitle:#"Video Recording Unavailable" msg:#"This device can't record video."];
}
}
- (void) stopSession
{
[session stopRunning];
[session release];
}
- (AVCaptureDevice *)frontFacingCameraIfAvailable
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *captureDevice = nil;
Boolean cameraFound = false;
for (AVCaptureDevice *device in videoDevices)
{
NSLog(#"1 frontFacingCameraIfAvailable %d", device.position);
if (device.position == AVCaptureDevicePositionBack){
NSLog(#"1 frontFacingCameraIfAvailable FOUND");
captureDevice = device;
cameraFound = true;
break;
}
}
if(cameraFound == false){
for (AVCaptureDevice *device in videoDevices)
{
NSLog(#"2 frontFacingCameraIfAvailable %d", device.position);
if (device.position == AVCaptureDevicePositionFront){
NSLog(#"2 frontFacingCameraIfAvailable FOUND");
captureDevice = device;
break;
}
}
}
return captureDevice;
}
- (AVCaptureDevice *) audioDevice
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
if ([devices count] > 0) {
return [devices objectAtIndex:0];
}
return nil;
}
- (void) startRecording
{
#if _Multitasking_
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{}]];
}
#endif
[videoOutput startRecordingToOutputFileURL:[self generatenewVideoPath]
recordingDelegate:self];
}
- (void) stopRecording
{
[videoOutput stopRecording];
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections error:(NSError *)error
{
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: [outputFileURL path] error: NULL];
NSString *fileSize = [NSString stringWithFormat:#"%llu", [attrs fileSize]];
// close this screen
[self exitScreen];
}
-(BOOL)recordsVideo
{
AVCaptureConnection *videoConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo
fromConnections:[videoOutput connections]];
return [videoConnection isActive];
}
-(BOOL)recordsAudio
{
AVCaptureConnection *audioConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeAudio
fromConnections:[videoOutput connections]];
return [audioConnection isActive];
}
If I do [videoInput release]; and [audioInput release]; I got a bad access error. that's why they are commented out. This may be part of the issue.
If I try to play the system sound n times, it work, but if I go first to the recording script, it wont work after that.
Any ideas?
The proper way to release AVCaptureSession is the following:
- (void) destroySession {
// Notify the view that the session will end
if ([delegate respondsToSelector:#selector(captureManagerSessionWillEnd:)]) {
[delegate captureManagerSessionWillEnd:self];
}
// remove the device inputs
[session removeInput:[self videoInput]];
[session removeInput:[self audioInput]];
// release
[session release];
// remove AVCamRecorder
[recorder release];
// Notify the view that the session has ended
if ([delegate respondsToSelector:#selector(captureManagerSessionEnded:)]) {
[delegate captureManagerSessionEnded:self];
}
}
If you're having some sort of release problems (bad access), I can recommend taking your code out of your current "messy" project to some other new project and debug the problem over there.
When I had similar problem, I just did that. I shared it on Github, you might find this project useful: AVCam-CameraReleaseTest

Why does the pushViewController stop working when I remove a UIAlertView

I outsourced some iPhone development and I am trying to make a simple change to the code, but it does not make any sense to me. I am hoping that someone can help me out. I would ask the original developer, but they just left for a week long vacation and I would prefer to not wait.
//
// SettingViewController.m
// FoodStorageManagement
//
// Created by Ryan McLaughlin on 10/20/11.
// Copyright 2011 Food Storage Management. All rights reserved.
//
#import "SettingViewController.h"
#import "MainViewController.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"
#import "XMLRPCConnection.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#implementation SettingViewController
#synthesize Obj_string,LoginState,hashkey,validuser,apikey,spinnerView;
-(id)init
{
[super init];
img_loginBg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Loginpage.png"]];
img_loginBg.frame=CGRectMake(0, 0, 320, 460);
app=[[UIApplication sharedApplication]delegate];
UserIDtxt=[[UITextField alloc]initWithFrame:CGRectMake(150, 163, 160, 25)];
UserIDtxt.returnKeyType=UIReturnKeyDone;
UserIDtxt.backgroundColor=[UIColor clearColor];
//UserIDtxt.text=#"user";
UserIDtxt.delegate=self;
UserIDtxt.tag=1;
pwdText=[[UITextField alloc]initWithFrame:CGRectMake(150, 220, 160, 25)];
pwdText.backgroundColor=[UIColor clearColor];
//pwdText.text=#"123456";
pwdText.secureTextEntry=YES;
pwdText.returnKeyType=UIReturnKeyDone;
pwdText.delegate=self;
pwdText.tag=2;
btn_SignUp=[UIButton buttonWithType:UIButtonTypeCustom];
btn_SignUp.frame=CGRectMake(45, 335, 95, 35);
btn_SignUp.backgroundColor=[UIColor clearColor];
[btn_SignUp setTitle:#"" forState:UIControlStateNormal];
[btn_SignUp addTarget:self action:#selector(ClickOnSignUp) forControlEvents:UIControlEventTouchUpInside];
[btn_SignUp retain];
btn_LogIn=[UIButton buttonWithType:UIButtonTypeCustom];
btn_LogIn.frame=CGRectMake(175, 335, 95, 35);
btn_LogIn.backgroundColor=[UIColor clearColor];
[btn_LogIn setTitle:#"" forState:UIControlStateNormal];
[btn_LogIn addTarget:self action:#selector(ClickOnLogIn) forControlEvents:UIControlEventTouchUpInside];
[btn_LogIn retain];
NSString *deviceVersion=[UIDevice currentDevice].systemVersion;
NSLog(#"%#",deviceVersion);
btn_Back=[UIButton buttonWithType:UIButtonTypeCustom];
btn_Back.frame=CGRectMake(8, 417, 50, 40);
btn_Back.backgroundColor=[UIColor clearColor];
[btn_Back setTitle:#"" forState:UIControlStateNormal];
[btn_Back addTarget:self action:#selector(ClickOnBack) forControlEvents:UIControlEventTouchUpInside];
[btn_Back retain];
return self;
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
[super loadView];
[self.view addSubview:img_loginBg];
[self.view addSubview:btn_SignUp];
[self.view addSubview:btn_LogIn];
[self.view addSubview:btn_Back];
[self.view addSubview:UserIDtxt];
[self.view addSubview:pwdText];
}
-(void)ClickOnSignUp
{
Connection=[[NetworkConnection alloc]initConnection];
if (Connection.isReachable)
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.foodstoragemanagement.com/signup.php"]];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Network Connection unavailable.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
-(void) startSpinner:(NSString*)type andDisplay:(NSString*)display{
//remove any existing spinners at this point
if(self.spinnerView)
{
[self.spinnerView.view removeFromSuperview];
self.spinnerView = nil;
}
self.spinnerView =[[[SpinnerModal alloc]initWithType:type andDisplay:display]autorelease];
//add this to the root view of the app
//ViewManager *viewMgr = [ViewManager getManager];
[self.view addSubview:self.spinnerView.view];
}
-(void) stopSpinner{
NSLog(#"SPINNER IS REMOVED");
[self.spinnerView.view removeFromSuperview];
self.spinnerView = nil;
}
-(void)ClickOnLogIn
{
Connection=[[NetworkConnection alloc]initConnection];
if (Connection.isReachable)
{
[self startSpinner:#"spinner" andDisplay:#"Loading"];
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(ClickOnLog) userInfo:nil repeats:NO];
}
else {
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Network Connection unavailable.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
[self stopSpinner];
}
}
-(void)ClickOnLog
{
NSDate* now = [NSDate date];
NSString *dateString=[[NSString alloc]init];
dateString = [now description];
dateString=[self dateInFormat:#"%s"];
NSString *username=[UserIDtxt.text lowercaseString];
NSString *username_reverse=[username reverseString];
NSString *password_hash=[self sha256:pwdText.text];
NSString *str=[NSString stringWithFormat:#"%#%#%#",username,password_hash,dateString];
str=[self sha256:str];
app.username=[NSMutableString stringWithString:username];
app.password=[NSMutableString stringWithString:password_hash];
//url from plist
NSString *server=[[NSString alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
server=[plistDict objectForKey:#"NewUrl"];
XMLRPCRequest *reqHello = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[UserIDtxt.text lowercaseString] forKey:#"username"];
[dict setValue:str forKey:#"hash_key"];
[dict setValue:dateString forKey:#"timestamp"];
[reqHello setMethod:#"user.get_api" withObjects:[NSArray arrayWithObjects:dict,nil]];
NSString *result=[self executeXMLRPCRequest:reqHello];
if ([result length]>0)
{
NSLog(#"OUTPUT %#",result);
NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser1=[[NSXMLParser alloc]initWithData:data];
[parser1 setDelegate:self];
[parser1 parse];
[reqHello release];
defaults = [NSUserDefaults standardUserDefaults];
app.defaultuser=[NSUserDefaults standardUserDefaults];
[defaults setObject: app.globalApi_key forKey: #"api_key"];
[defaults setObject:UserIDtxt.text forKey:#"username"];
[defaults setObject:pwdText.text forKey:#"password"];
app.defaultuser=defaults;
if (!app.globalApi_key)
{
defaults = [NSUserDefaults standardUserDefaults];
}
[defaults synchronize];
if (!val)
{
val=[defaults objectForKey:#"api_key"];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Unable to communicate with the server" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
if( ![result isKindOfClass:[NSString class]] )//error occured
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"unable to communicate with server" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
else
{
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
[self stopSpinner];
}
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if([ConfirmationAlert.title isEqualToString:#"Authentication"])
{
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
}
}
# pragma mark Parsing Delegate Methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"params"])
{
Obj_string = [[NSMutableString alloc]init];
LoginState =[[NSMutableString alloc]init];
hashkey=[[NSMutableString alloc]init];
validuser=[[NSMutableString alloc]init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"name"])
{
self.LoginState=self.Obj_string;
}
else if([elementName isEqualToString:#"string"])
{
//NSLog(#"%#",Obj_string);
if([self.LoginState isEqualToString:#"hash_key"])
{
self.hashkey=self.Obj_string;
app.globalhash_key=self.hashkey;
}
if([self.LoginState isEqualToString:#"api"])
{
self.apikey=self.Obj_string;
app.globalApi_key=self.apikey;
}
if([self.LoginState isEqualToString:#"message"])
{
self.validuser=self.Obj_string;
}
}
[Obj_string release];
Obj_string = nil;
Obj_string = [[NSMutableString alloc]init];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[Obj_string appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
//[LoginState appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
-(NSString *)dateInFormat:(NSString*)stringFormat {
char buffer[80];
const char *format = [stringFormat UTF8String];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, format, timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}
- (NSString *)sha256:(NSString *)str
{
const char *inputString = [str UTF8String];
unsigned char hashedChars[32]; // 32bit encoding
//unsigned char hashedChars[64]; // 64 bit encoding
//unsigned char hashedChars[64]; //16 bit encoding
CC_SHA256(inputString , strlen(inputString), hashedChars);
NSData *hashedData = [NSData dataWithBytes:hashedChars length:32];//32bit encoding
//NSData *hashedData = [NSData dataWithBytes:hashedChars length:64]; //64bit encoding
//NSData *hashedData = [NSData dataWithBytes:hashedChars length:16]; //16bit encoding
NSLog(#"hashedData = %#", hashedData);
NSString *someString = [NSString stringWithFormat:#"%#", hashedData];
someString = [someString stringByReplacingOccurrencesOfString:#" " withString:#""];
someString = [someString stringByReplacingOccurrencesOfString:#"<" withString:#""];
someString = [someString stringByReplacingOccurrencesOfString:#">" withString:#""];
//return hash;
return someString;
}
- (NSString *)getMD5FromString:(NSString *)source
{
const char *src = [source UTF8String];
unsigned char result[16];
CC_MD5(src, strlen(src), result);
NSString *ret = [[[NSString alloc] initWithFormat:#"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] autorelease];
return [ret lowercaseString];
}
- (id)executeXMLRPCRequest:(XMLRPCRequest *)req
{
XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
return [userInfoResponse object];
}
-(void)ClickOnBack
{
[self dismissModalViewControllerAnimated:YES];
//[self.navigationController popViewControllerAnimated:YES];
//MainViewController *mainView=[[MainViewController alloc]init];
// [self.navigationController popToViewController:mainView animated:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
-(NSString*) digest:(NSString*)input
{
NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// uint8_t digest[CC_SHA1_DIGEST_LENGTH];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
// for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x", digest[i]];
return output;
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
The part in question is this
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
On the surface it seems really simple. The change I want to make is to remove this alert
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
However, any change to the alert causes the pushViewController to stop working. I have tried commenting the alert out,
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
// UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
//[LoginOK show];
//[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
I have tried rewriting the second if
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==FALSE)
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
I have also tried completely removing the second if
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
But the pushViewController will not work unless I have the alert in the code. I don't get any error, and the app does not crash, it just stays in the current page, so I am completely at a loss. It makes me think their is some action that is triggered by clicking "OK" in the alert, but I don't see anything in the code.
I have also stepped through the code to see if I can spot the problem but it seems fine.
In case it matters I am using xcode 4.2 and iOS 5 sdk.
Another strange occurance is that if I run the code like this
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
and I get a login error (meaning it triggers the alert in the else). Then after clicking ok it moves on to the next page. I really don't understand how this could happen since they are in different part of the if. I must be missing something obvious.
The Uialertview delegate method never gets called, therefore never dismisses the modal view controller
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
Just dismiss the view controller next to the commented code
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
I may be totally off base here, but did you try removing the entire block;
if (app.Authorisation==TRUE)
{ ***STARTING HERE
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
} ***ENDING HERE
}
If you remove the alert then the delegate methods won't be called.
This part here:
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex {
if([ConfirmationAlert.title isEqualToString:#"Authentication"]) {
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
}
}
Just put the code inside the if-block above into the block where you removed the alert.

iPhone: Delegate method not being called for AVAudioPlayer and AVAudioRecorder

The problem I am facing is with play. When I record that is storing in document directory with format of document even with size that means recording is being done. And when my play function is calling I am converting it to NSData, though it is not playing anything.
- (void)record{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
NSLog(#"audioSession: %# %d %#", [err domain], [err code], [[err userInfo] description]);
return;
}
if(recorder)
{
if(recorder.recording)
[recorder stop];
[recorder release];
recorder = nil;
}
NSString *fileName = nil;
if(![myItem audioURL]){
fileName = [fileFormatter stringFromDate:[NSDate date]];
[myItem setAudioURL:fileName];
} else{
fileName = [myItem audioURL];}
NSString *pathString = [NSString stringWithFormat:#"%#/%#", [delegate applicationDocumentsDirectory], fileName];
NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleIMA4],AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax],AVEncoderAudioQualityKey,nil];
recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:pathString] settings: recordSettings error: nil];
recorder.delegate = self;
if ([recorder prepareToRecord] == YES){
[recorder record];
recording = YES;
[pauseButton setImage:[UIImage imageNamed:#"stop.png"] forState:UIControlStateNormal];
[pauseButton setEnabled:YES];
[playButton setEnabled:NO];
[recordButton setEnabled:NO];
[self beginAnimation];
// NSError *error=nil;
// if(![context save: &error])
// {
// //Couldn't save
// }
}
}
- (void)play{
/* [self silenced];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),&audioRouteOverride);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
*/
if(pausedPlayback){
[player play];
playing = YES;
pausedPlayback = NO;
[pauseButton setEnabled:YES];
[playButton setEnabled:NO];
[self beginAnimation];
return;
}
NSString *fileName = nil;
if(![myItem audioURL]){
return;
} else
fileName = [myItem audioURL];
NSLog(#"file name :%#",fileName);
// NSError *error;
NSString *pathString = [NSString stringWithFormat:#"%#/%#", [delegate applicationDocumentsDirectory], fileName];
NSLog(#"Path : %#",pathString);
// player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:pathString] error:nil] ;
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pathString]];
player = [[AVAudioPlayer alloc] initWithData:soundData error: nil];
player.delegate = self;
player.volume=1.0;
// Play the audio
[player prepareToPlay];
[player play];
playing = YES;
[recordButton setEnabled:NO];
[pauseButton setEnabled:YES];
[playButton setEnabled:NO];
// if (player==nil) {
// NSLog(#"%#",[error description]);
// }
// else
// {
/* player.volume=1.0;
NSLog(#"about to play");
[player prepareToPlay];
[player play];
NSLog(#"player play");
[player setDelegate:self];
playing = YES;
[recordButton setEnabled:NO];
[pauseButton setEnabled:YES];
[playButton setEnabled:NO];*/
[self beginAnimation];
// }
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)_recorder successfully:(BOOL)flag{
NSLog (#"audioRecorderDidFinishRecording:successfully:");
[recorder release];
recorder = nil;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)_player successfully:(BOOL)flag{
if(![player isPlaying])
{
[player stop];
}
[player release];
player = nil;
playing = NO;
[playButton setEnabled:YES];
[pauseButton setEnabled:NO];
[recordButton setEnabled:YES];
[self stopAnimation];
}