How to record ,save and playback sound using AVAudioRecorder in Xcode

- (IBAction)recordAction:(UIButton *)sender {
    NSError *error;
    
    NSLog(@"recording");
    
    // Recording settings
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];
    
    [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
    [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    [settings setValue:  [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];
    
    NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath_ = [searchPaths objectAtIndex: 0];
    
    NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
    
    // File URL
    NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];
    NSLog(@"url = %@",url);
    
    
    //Save recording path to preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    
    [prefs setURL:url forKey:@"Test1"];
     NSLog(@"prefs = %@",prefs);
    [prefs synchronize];
    
    
    // Create recorder
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
    [recorder setDelegate:self];

    recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    [recorder prepareToRecord];
    //recorder.delegate = self;
    [recorder record];
    
    
}
- (IBAction)stopRecording:(UIButton *)sender {
     //Stop recording
    [recorder stop];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

- (IBAction)playRecord:(UIButton *)sender {
    //to play recorded sound
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    //Load recording path from preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    temporaryRecFile = [prefs URLForKey:@"Test1"];
    NSLog(@"temporaryRecFile = %@",temporaryRecFile);
    
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
    player.delegate = self;
    [player setNumberOfLoops:0];
    player.volume = 1;
    [player prepareToPlay];
    [player play];
    
}

- (NSString *) dateString
{
    // return a formatted string for a file name
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"ddMMMYY_hhmmssa";
    return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".aif"];
}

How to save/export iPhone library music into our app?

-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
    
    MPMediaItem *item=[mediaItemCollection representativeItem];
    url = [item valueForProperty: MPMediaItemPropertyAssetURL];
    NSLog(@"url == %@",url);
    
    song = [mediaItemCollection representativeItem];//[[mediaItemCollection items] objectAtIndex:0];
    
    [self dismissModalViewControllerAnimated: YES];
    
    [self handleExportAudio];

}

-(void) handleExportAudio {
    // get the special URL
    NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    
    NSLog (@"compatible presets for songAsset: %@",
           [AVAssetExportSession exportPresetsCompatibleWithAsset:songAsset]);
    
    
    /* approach 1: export just the song itself
     */
    exporter = [[AVAssetExportSession alloc]
                                      initWithAsset: songAsset
                                      presetName: AVAssetExportPresetAppleM4A];
    NSLog (@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
    exporter.outputFileType = @"com.apple.m4a-audio";
    NSString *exportFile = [myDocumentsDirectory() stringByAppendingPathComponent: @"exported.m4a"];
    
    // set up export (hang on to exportURL so convert to PCM can find it)
    myDeleteFile(exportFile);
    exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;
    
    NSLog(@"exportURL = %@",exportURL);
    
    // do the export
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        int exportStatus = exporter.status;
        switch (exportStatus) {
            case AVAssetExportSessionStatusFailed: {
                // log error to text view
                NSError *exportError = exporter.error;
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                break;
            }
            case AVAssetExportSessionStatusCompleted: {
                NSLog (@"AVAssetExportSessionStatusCompleted");
                break;
            }
            case AVAssetExportSessionStatusUnknown: { NSLog (@"AVAssetExportSessionStatusUnknown"); break;}
            case AVAssetExportSessionStatusExporting: { NSLog (@"AVAssetExportSessionStatusExporting"); break;}
            case AVAssetExportSessionStatusCancelled: { NSLog (@"AVAssetExportSessionStatusCancelled"); break;}
            case AVAssetExportSessionStatusWaiting: { NSLog (@"AVAssetExportSessionStatusWaiting"); break;}
            default: { NSLog (@"didn't get export status"); break;}
        }
    }];
    
}

#pragma mark conveniences
NSString* myDocumentsDirectory() {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];;
}

void myDeleteFile (NSString* path) {
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *deleteErr = nil;
        [[NSFileManager defaultManager] removeItemAtPath:path error:&deleteErr];
        if (deleteErr) {
            NSLog (@"Can't delete %@: %@", path, deleteErr);
        }
    }
}

- (IBAction)playAudio:(UIButton *)sender {
    
    NSLog(@"DOcs dir = %@", myDocumentsDirectory());
    NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://localhost%@/exported.m4a",myDocumentsDirectory()]];
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:myURL error:nil];
    [player play];
}

Saving images to database using sql in ios

// Create Table.
sql_statement = "CREATE TABLE IF NOT EXISTS IMAGES (IMAGE BLOB)";
if( sqlite3_exec(myDB, sql_statement, NULL, NULL, &errMsg) != SQLITE_OK)
    NSLog( @"Fail to create  table");

// funtion to save image
- (void) SaveImagesToDatabase: (NSData*) imageData
{
    const char* sqliteQuery = "INSERT INTO IMAGES (IMAGE) VALUES (?)";
    sqlite3_stmt* statement;

    if( sqlite3_prepare_v2(myDB, sqliteQuery, -1, &statement, NULL) == SQLITE_OK ) 
       { 
         sqlite3_bind_blob(statement, 2, [imageData bytes], [imageData length], SQLITE_TRANSIENT); 
         sqlite3_step(statement);
        } 
         else 
            NSLog( @"prepare failed");
 // Finalize and close database. 
      sqlite3_finalize(statement); 
}

Creating a singleton class in objective C

@implementation MySingleton static MySingleton* _sharedMySingleton = nil;
+(MySingleton*)sharedMySingleton
{
@synchronized([MySingleton class])
{
if (!_sharedMySingleton) [[self alloc] init];   return _sharedMySingleton;                       }
return nil;
}
+(id)alloc
{
@synchronized([MySingleton class])
{
NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second     instance of a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}   return nil;
}
 
-(id)init
{
self = [super init];
if (self != nil)
{
// initializations
}
return self;
}

Fixing Undefined Symbols While Integrating Testflight in IOS

The common undefined symbol error appearing while integrating test flight will be something like the following :

Undefined symbols for architecture armv7s:

“_deflateInit_”, referenced from:

_compress_data in libTestFlight.a(tf_compression.o)

“_deflateEnd”, referenced from:

_compress_data in libTestFlight.a(tf_compression.o)

“_deflate”, referenced from:

_compress_data in libTestFlight.a(tf_compression.o)

ld: symbol(s) not found for architecture armv7s

clang: error: linker command failed with exit code 1 (use -v to see invocation)

 

The fix for this issue is simple.

Goto the build phases of the target for which the issue is appearing. In the link binary with libraries section, use the ‘+’ button at the bottom to add a new library. In the dialog box which appears, search for libz.dylib . You will see the library in the list. Select that and press the ‘Add’ button.

Now perform a build clean for the project and you are done.

Build the app and the issue will be fixed.

Getting the Child View Controllers of a View Controller in Xcode

We can get the child view controllers of a view controller using the childViewControllers property of the view controller.

If we are in a view controller class, if we want to get its child view controllers, then we can use the following code :

self.childViewControllers;

This will return an array of view controllers that are the child of the current view controller.

If there are no child view controllers of the current view controller, then the array will be empty.

 

If we are to get the child view controllers of a navigation controller, we can use the following code :

self.navigationController.childViewControllers;