NSMutableArray writeToURL:url atomically:YES - objective-c

I'm trying to create a file with an NSMutableArray with just NSStrings stringWithFormat objects inside, this is what i got:
- (IBAction)CreateMod:(id)sender {
NSLog(#"Finished Button Pressed");
NSString* CustomScript = [NSString stringWithFormat:#"//Made with UltimateMM \n %#",self.CS ];
NSArray* fileTypes = [[NSArray alloc] initWithObjects:#"js", nil];
NSSavePanel *spanel = [NSSavePanel savePanel];
[spanel setCanCreateDirectories:YES];
[spanel setCanSelectHiddenExtension:YES];
[spanel setAllowedFileTypes:fileTypes];
[spanel setTreatsFilePackagesAsDirectories:YES];
[spanel beginSheetModalForWindow:self.SecondaryWindow completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton)
{
NSURL *saveURL = [spanel URL];
NSLog(#"%#", saveURL);
NSError* error = nil;
if(_CST == true) {
NSLog(#"CustomScriptMade");
/*
BOOL didWrite = [CustomScript writeToURL:saveURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (didWrite == NO)
{
NSLog(#"CustomScript Write Error");
}
*/
}
if(_TTT == true) {
NSLog(#"TopicMade");
BOOL didWrite = [_TopicPR writeToURL:saveURL atomically:YES];
if (didWrite == NO)
{
NSLog(#"Topic Write Error");
}
}
_CST = false;
_TTT = false;
}
}];
}
I have the CustomScript writeToURL out so i can see if it crates the TopicPR, but it doesn't even open the NSSavePanel, Please Help.
thanks in advance!..

Related

How to access smart folder from gallery using ALAsset

I am making an app where I want to get the list of all albums name from gallery including smart folders(favorites, screenshots. this is an old app where we have used ALAsset in order to access the gallery in our app.
Is there any way through which we can access smart folders as well using ALAssetLibrary?
This code is help.
#import <AssetsLibrary/AssetsLibrary.h>
#property (nonatomic, strong) ALAssetsLibrary *_assetsLibrary;
- (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred, ^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
-(void) getgalleryPic
{
if (self.photos == nil) {
self.photos = [[NSMutableArray alloc] init];
}else
{
[self.photos removeAllObjects];
}
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized) {
// Access has been granted.
NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
ALAssetsLibrary *library = [self defaultAssetsLibrary];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset) {
[collector addObject:asset];
}else
{
self.photos = [[[collector reverseObjectEnumerator] allObjects] mutableCopy];
NSLog(#"photo lenght %lu",(unsigned long)[self.photos count]);
[_collectionVW reloadData];
}
}];
}
failureBlock:^(NSError *error) { NSLog(#"Boom!!!");}
];
}
else if (status == PHAuthorizationStatusDenied) {
// Access has been denied.
}
else if (status == PHAuthorizationStatusNotDetermined) {
// Access has not been determined.
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
// Access has been granted.
NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
ALAssetsLibrary *library = [self defaultAssetsLibrary];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset) {
[collector addObject:asset];
}else
{
self.photos = [[[collector reverseObjectEnumerator] allObjects] mutableCopy];
NSLog(#"photo lenght %lu",(unsigned long)[self.photos count]);
[_collectionVW reloadData];
}
}];
}
failureBlock:^(NSError *error) { NSLog(#"Boom!!!");}
];
}
else {
// Access has been denied.
}
}];
} else if (status == PHAuthorizationStatusRestricted) {
// Restricted access - normally won't happen.
}
}

Check if function returns true Objective-C

I am wanting to check that when a function returns a true value then NSLog(#"hello!!!"); Just to confirm, I wish to check that validUrl returns true. I have declared the controller that it is inside, and this is the complete code:
NewInAppWebViewController *webViewController = [[NewInAppWebViewController alloc] init];
if([webViewController validUrl:(NSURL *)url] == true) {
NSLog(#"hello!!!");
}
else
{
[self showAlertForExternalURL:url];
}
Below is the function:
- (BOOL)validUrl:(NSURL*)url {
NSString *stringURL = [url absoluteString];
if([stringURL length]==0){
return false;
}
NSString *regExPattern = #"www-(test|testing[a-z]|newtest)\.testerer\.com";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:stringURL options:0 range:NSMakeRange(0, [stringURL length])];
NSLog(#"%i", regExMatches);
if (regExMatches == 0) {
return false;
} else {
return true;
}
}
Try below code:
Pass NSURL to method parameter and call method as follows:
NewInAppWebViewController *webViewController = [[NewInAppWebViewController alloc] init];
NSURL *url=yourNSURLHere;
if([webViewController validUrl:url]) {
NSLog(#"hello!!!");
}
else{
[self showAlertForExternalURL:url];
}

Working with SQLite in IOS

Hello, I am using following code to implement SQLite Database in Application. Friends have you any other easiest way to implement
this, Which work with all the content of SQLite Database.
// .h File of DBManager
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface DBOperation : NSObject
{
}
+(void)OpenDatabase:(NSString*)path; //Open the Database
//+(void)finalizeStatements;//Closing and do the final statement at application exits
+(void)checkCreateDB;
//+(int) getLastInsertId;
+(BOOL) executeSQL:(NSString *)sqlTmp;
+(NSMutableArray*) selectData:(NSString *)sql;
#end
//
// DBOperation.m
// Puzzle
//
// Created by hbmac1 on 9/22/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "DBOperation.h"
static sqlite3 *database = nil;
static int conn;
#implementation DBOperation
+(void)checkCreateDB
{
#try {
NSString *dbPath,*databaseName;
databaseName=#"pointtable.sqlite";
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [docPaths objectAtIndex:0];
dbPath = [docDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fm = [NSFileManager defaultManager];
success=[fm fileExistsAtPath:dbPath];
if(success)
{
[self OpenDatabase:dbPath];
return;
}
NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
[self OpenDatabase:dbPath];
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
}
}
//Open database
+ (void) OpenDatabase:(NSString*)path
{
#try
{
conn = sqlite3_open([path UTF8String], &database);
if (conn == SQLITE_OK) {
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
#catch (NSException *e) {
NSLog(#"%#",e);
}
}
+(NSMutableArray*) selectData:(NSString *)sql
{
#try
{
if (conn == SQLITE_OK)
{
sqlite3_stmt *stmt = nil;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
[NSException raise:#"DatabaseException" format:#"Error while creating statement. '%s'", sqlite3_errmsg(database)];
}
NSMutableArray *obj = [[NSMutableArray alloc]init];
int numResultColumns = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
numResultColumns = sqlite3_column_count(stmt);
#autoreleasepool {
NSMutableDictionary *tmpObj = [[NSMutableDictionary alloc]init];
for(int i = 0; i < numResultColumns; i++){
if(sqlite3_column_type(stmt, i) == SQLITE_INTEGER){
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%i",sqlite3_column_int(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%f",sqlite3_column_double(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
if ( tmpStr == nil) {
tmpStr = #"";
}
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_BLOB) {
}
else if (sqlite3_column_type(stmt, i) == SQLITE_NULL) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = #"";
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
}
}
[obj addObject:tmpObj];
}
}
return obj;
} else {
return nil;
}
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return nil;
}
}
+(BOOL) executeSQL:(NSString *)sqlTmp {
#try {
if(conn == SQLITE_OK) {
const char *sqlStmt = [sqlTmp cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *cmp_sqlStmt1;
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt1, NULL);
returnValue == SQLITE_OK ? NSLog(#"\n Inserted \n") :NSLog(#"\n Not Inserted \n");
sqlite3_step(cmp_sqlStmt1);
sqlite3_finalize(cmp_sqlStmt1);
if (returnValue == SQLITE_OK)
{
return TRUE;
}
}
return FALSE;
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return NO;
}
}
#end
Check FMDB, it is very powerful and a lot easier to work with
(void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; NSFileManager *filemgr=[NSFileManager defaultManager]; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { char *errmsg; const char *sql_stmt="CREATE TABLE IF NOT EXISTS EVENT(EVENTID INTEGER PRIMARY KEY AUTOINCREMENT,ENAME TEXT,ETIME TEXT,TIMAGE TEXT)"; if(sqlite3_exec(eventDb,sql_stmt,NULL,NULL,&errmsg)!=SQLITE_OK) { NSLog(#"falied"); } sqlite3_close(eventDb); } else { NSLog(#"failed to open/create database"); }} //insert dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; sqlite3_stmt *statement; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { { { NSString *insertSQL=[NSString stringWithFormat:#" INSERT INTO EVENT(ENAME,ETIME,TIMAGE) VALUES (\"%#\",\"%#\",\"%#\")",_eventLbl.text,time,name]; const char *insert_stmt=[insertSQL UTF8String]; sqlite3_prepare_v2(eventDb,insert_stmt,-1,&statement,NULL); if(sqlite3_step(statement)==SQLITE_DONE) { NSLog(#"added"); } else { NSLog(#"fail to added"); } }}} //select NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; const char *dbpath=[databasePath UTF8String]; sqlite3_stmt *statment; if(sqlite3_open(dbpath,&eventDb)==SQLITE_OK) { NSString *querySQL=[NSString stringWithFormat:#"SELECT ENAME,ETIME,TIMAGE FROM EVENT "]; const char *query_stmt=[querySQL UTF8String]; if(sqlite3_prepare_v2(eventDb,query_stmt,-1,&statment,NULL)==SQLITE_OK) { while(sqlite3_step(statment)==SQLITE_ROW) { NSString ename=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 0)]; NSString eTIme=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 1)]; NSString IMAGENAME=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 2)]; event *g=[[event alloc] init]; g.eventname=ename; g.eventime=eTIme; g.eventImagename=IMAGENAME; [_arr addObject:g] } sqlite3_finalize(statment); } sqlite3_close(eventDb); } //tableview -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_tool count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *myId=#"myID"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:myId]; if (cell==nil) { [[NSBundle mainBundle]loadNibNamed:#"royalkitCell" owner:self options:nil]; cell=_toolCell; cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; } NSString *tname=[_tool objectAtIndex:indexPath.row]; _toolLabel=(UILabel *)[cell viewWithTag:10]; _toolLabel.text=tname; return cell; } Heading

AVAssetWriter goes AVAssetWriterStatusFailed after appendSampleBuffer:

I am trying to perform screen-recording using AVAssetWriter, which also accepts audio input. However, I have been stuck on this error, where AVAssetWriter sometimes becomes AVAssetWriterStatusFailed after a few calls on appendSampleBuffer: (inside encodeAudioFrame:)
Failed: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo=0x32b570 {NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x70d710 "The operation couldn’t be completed. (OSStatus error -12737.)", NSLocalizedFailureReason=An unknown error occurred (-12737)}
Several observations:
Once it enters this state, subsequent recording attempts will also return AVAssetWriterStatusFailed, even if I use a different recorder object.
The error does not appear when I comment out the audio recording blocks.
But the error still appears when I comment out the video recording blocks, and without modifying any incoming CMSampleBufferRef.
Any assistance will be appreciated.
Below is the code I am using, with several parts omitted for brevity. I am currently using OSX 10.9 SDK, with ARC turned off.
- (BOOL) startRecording
{
if (!isRecording)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self startCapture];
[self setUpWriter];
startedAt = [NSDate date];
isRecording = YES;
while (isRecording)
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
NSTimeInterval offset = [[NSDate date] timeIntervalSinceDate:startedAt];
CMTime tiem = CMTimeMakeWithSeconds(offset - pauseDelta, 1000);
[self encodeFrameAtTime:tiem];
[pool drain];
sleep(0.05f);
}
[self endCapture];
[self completeRecordingSession];
});
}
return YES;
}
- (void) stopRecording {
isRecording = NO;
}
-(void) startCapture
{
AVCaptureDevice* microphone = x //Device selection code omitted
videoCaptureSession = [[AVCaptureSession alloc] init];
videoCaptureSession.sessionPreset = AVCaptureSessionPresetHigh;
//------------------------------------------
NSError* err = nil;
audioInput = [AVCaptureDeviceInput deviceInputWithDevice:microphone error:&err];
[videoCaptureSession addInput:audioInput];
//------------------------------------------
audioOutput = [[AVCaptureAudioDataOutput alloc] init];
queue = dispatch_queue_create("videoQueue", NULL);
[audioOutput setSampleBufferDelegate:self queue:queue];
[videoCaptureSession addOutput:audioOutput];
audioDelta = -1;
[videoCaptureSession startRunning];
}
-(void) endCapture
{
[videoCaptureSession stopRunning];
[videoCaptureSession removeInput:audioInput];
[videoCaptureSession removeOutput:audioOutput];
[audioOutput release];
audioOutput = nil;
audioInput = nil;
[videoCaptureSession release];
videoCaptureSession = nil;
dispatch_release(queue);
}
-(BOOL) setUpWriter
{
//delete the file.
{
NSFileManager* fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:self.moviePath]) {
NSError* error;
if ([fileManager removeItemAtPath:self.moviePath error:&error] == NO) {
NSLog(#"Could not delete old recording file at path: %#", self.moviePath);
}
}
}
mCaptureRect = NSRectToCGRect([screen frame]);
int FWidth = mCaptureRect.size.width;
int FHeight = mCaptureRect.size.height;
int bitRate = FWidth * FHeight * 8;
videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:self.moviePath] fileType:AVFileTypeMPEG4 error:nil];
NSParameterAssert(videoWriter);
//Configure video
NSDictionary *codecSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:bitRate], AVVideoAverageBitRateKey,
nil];
NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
codecSettings,AVVideoCompressionPropertiesKey,
[NSNumber numberWithInt:FWidth], AVVideoWidthKey,
[NSNumber numberWithInt:FHeight], AVVideoHeightKey,
nil];
videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
NSParameterAssert(videoWriterInput);
videoWriterInput.expectsMediaDataInRealTime = YES;
NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey,
[NSNumber numberWithInt:FWidth], kCVPixelBufferWidthKey,
[NSNumber numberWithInt:FHeight], kCVPixelBufferHeightKey,
nil];
avAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:bufferAttributes];
//*
//Configure Audio
AudioChannelLayout acl;
bzero(&acl, sizeof(acl));
acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
NSDictionary* audioSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
[ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
[ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
[ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
[NSNumber numberWithInt:64000], AVEncoderBitRateKey,
nil ];
audioWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:audioSettings];
audioWriterInput.expectsMediaDataInRealTime = YES;
//add input
[videoWriter addInput:videoWriterInput];
[videoWriter addInput:audioWriterInput];
return YES;
}
- (void) cleanupWriter {
[videoWriter release];
videoWriter = nil;
avAdaptor = nil;
videoWriterInput = nil;
startedAt = nil;
audioWriterInput = nil;
}
- (void) encodeFrameAtTime:(CMTime)timestamp
{
if(!isRecording) return;
if(videoWriter == nil) return;
if(videoWriter.status == AVAssetWriterStatusFailed)
{
return;
}
if(videoWriter.status != AVAssetWriterStatusWriting)
{
if(videoWriter.status != AVAssetWriterStatusUnknown)
return;
[videoWriter startWriting];
[videoWriter startSessionAtSourceTime:timestamp];
startTime = CMTimeGetSeconds(timestamp);
}
timestamp = CMTimeMakeWithSeconds(startTime + CMTimeGetSeconds(timestamp), 1000);
[self writeVideoFrameAtTime:timestamp];
}
-(void) writeVideoFrameAtTime:(CMTime)time {
if (![videoWriterInput isReadyForMoreMediaData])
{
}
else
{
/*
CVPixelBufferRef manipulation omitted...
*/
{
BOOL success = [avAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:time];
if(videoWriter.status == AVAssetWriterStatusFailed) NSLog(#"Failed: %#", videoWriter.error);
if (!success) NSLog(#"Warning: Unable to write buffer to video");
}
CVPixelBufferRelease(pixelBuffer);
CGImageRelease(cgImage);
}
}
-(void) encodeAudioFrame:(CMSampleBufferRef)buffer
{
if(!isRecording) return;
CMTime timestamp = CMSampleBufferGetPresentationTimeStamp(buffer);
if(videoWriter.status != AVAssetWriterStatusWriting)
{
//Wait for video thread to start the writer
return;
}
if(![audioWriterInput isReadyForMoreMediaData])
return;
//*
NSTimeInterval offset = [[NSDate date] timeIntervalSinceDate:startedAt];
if(audioDelta == -1)
{
audioDelta = offset - CMTimeGetSeconds(timestamp);
}
//Adjusts CMSampleBufferRef's timestamp to match the video stream's zero-based timestamp
CMItemCount count;
CMTime newTimestamp = CMTimeMakeWithSeconds(CMTimeGetSeconds(timestamp) + audioDelta - pauseDelta, 1000);
CMSampleBufferGetSampleTimingInfoArray(buffer, 0, nil, &count);
CMSampleTimingInfo* pInfo = malloc(sizeof(CMSampleTimingInfo) * count);
CMSampleBufferGetSampleTimingInfoArray(buffer, count, pInfo, &count);
for(CMItemCount i = 0; i < count; i++)
{
pInfo[i].decodeTimeStamp = newTimestamp;
pInfo[i].presentationTimeStamp = newTimestamp;
}
CMSampleBufferRef newBuffer;
CMSampleBufferCreateCopyWithNewTiming(kCFAllocatorDefault, buffer, count, pInfo, &newBuffer);
free(pInfo);
timestamp = CMSampleBufferGetPresentationTimeStamp(newBuffer);
BOOL res = [audioWriterInput appendSampleBuffer:newBuffer];
}
- (void) completeRecordingSession {
#autoreleasepool {
if(videoWriter.status != AVAssetWriterStatusWriting)
{
while (videoWriter.status == AVAssetWriterStatusUnknown)
{
[NSThread sleepForTimeInterval:0.5f];
}
int status = videoWriter.status;
while (status == AVAssetWriterStatusUnknown)
{
NSLog(#"Waiting...");
[NSThread sleepForTimeInterval:0.5f];
status = videoWriter.status;
}
}
#synchronized(self)
{
[videoWriter finishWriting];
[self cleanupWriter];
}
}
}
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
if(!CMSampleBufferDataIsReady(sampleBuffer))
return;
#autoreleasepool {
if(captureOutput == audioOutput)
{
if(isRecording && !isPaused)
{
[self encodeAudioFrame:sampleBuffer];
}
}
}
}
I had exactly the same problem with my swift code. I found out that my pc simply ran out of memory. So double check if you have enough free ram.

App crashing after selecting audio in iOS 7, fine on iOS 6

When selecting a song from the users library on either iPhone or iPad devices running iOS7 my app crashes out
The line it stops on is
FourCharCode formatID = audioDesc->mFormatID;
With a EXC_BAD_ACCESS code
Trying to check the console for more info, this is the last step it mentions;
appMake[8392:60b] Select music AssetUrl = (null)
Code below for the export session part;
- (void)exportAssetAsSourceFormat:(MPMediaItem *)item {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:songAsset
presetName:AVAssetExportPresetPassthrough];
NSArray *tracks = [songAsset tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack *track = [tracks objectAtIndex:0];
id desc = [track.formatDescriptions objectAtIndex:0];
const AudioStreamBasicDescription *audioDesc = CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)desc);
FourCharCode formatID = audioDesc->mFormatID;
NSString *fileType = nil;
NSString *ex = nil;
switch (formatID) {
case kAudioFormatLinearPCM:
{
UInt32 flags = audioDesc->mFormatFlags;
if (flags & kAudioFormatFlagIsBigEndian) {
fileType = #"public.aiff-audio";
ex = #"aif";
} else {
fileType = #"com.microsoft.waveform-audio";
ex = #"wav";
}
}
break;
case kAudioFormatMPEGLayer3:
fileType = #"com.apple.quicktime-movie";
ex = #"mp3";
break;
case kAudioFormatMPEG4AAC:
fileType = #"com.apple.m4a-audio";
ex = #"m4a";
break;
case kAudioFormatAppleLossless:
fileType = #"com.apple.m4a-audio";
ex = #"m4a";
break;
default:
break;
}
exportSession.outputFileType = fileType;
NSString *exportPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:[EXPORT_NAME stringByAppendingPathExtension:ex]] retain];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
NSLog(#"export session completed");
//return YES;
[self performSelectorOnMainThread:#selector(gotoMainView:)
withObject:[EXPORT_NAME stringByAppendingPathExtension:ex]
waitUntilDone:NO];
} else {
NSLog(#"export session error");
//return NO;
}
[exportSession release];
}];
[pool release];
}
Media picker code;
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
// Dismiss the media item picker.
[self dismissModalViewControllerAnimated: YES];
if ([mediaItemCollection count] < 1) {
return;
}
[selectedItem release];
selectedItem = [[[mediaItemCollection items] objectAtIndex:0] retain];
NSURL* filePath = [selectedItem valueForProperty: MPMediaItemPropertyAssetURL];
NSLog(#"Select music AssetUrl = %#", filePath);
[viewLoading setHidden:NO];
[self UnloadSound];
[NSThread detachNewThreadSelector:#selector(exportAssetAsSourceFormat:) toTarget:self withObject:selectedItem];
}