Tuesday, April 30, 2013

NSURL fileURLWithPathComponents example ios


fileURLWithPathComponents:

Initializes and returns a newly created NSURL object as a file URL with specified path components.
+ (NSURL *)fileURLWithPathComponents:(NSArray *)components
Parameters
components
An array of path components.
Passing nil for this parameter produces an exception.
Return Value of [NSURL fileURLWithPathComponents]
An NSURL object initialized with components.
Discussion of [NSURL fileURLWithPathComponents]
The path components are separated by a forward slash in the returned URL.
Example of [NSURL fileURLWithPathComponents] - 1

[audioManager setOutputBlock:^(float *data, UInt32 numFrames, UInt32 numChannels)
 {
     if( ![fileReader playing] ){

//      [fileReader release]; // for some reason this is causing an error, but I assume if you don´t do it, it will eventually cause a memory problem
//      fileReader = nil;

        [self playSound];
     } else {
         [fileReader retrieveFreshAudio:data numFrames:numFrames numChannels:numChannels];         
         NSLog(@"Time: %f", [fileReader getCurrentTime]);
    }
 }];

- (void) playSound
{
    NSArray *pathComponents = [NSArray arrayWithObjects:
                           [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
                           @"testrecording.wav",
                           nil];
    NSURL *inputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    NSLog(@"URL: %@", inputFileURL);

    fileReader = [[AudioFileReader alloc]
                  initWithAudioFileURL:inputFileURL
                  samplingRate:audioManager.samplingRate
                  numChannels:audioManager.numOutputChannels];

    [fileReader play];
    [fileReader setCurrentTime:0.0]; 
    //float duration = fileReader.getDuration;
}

Example of [NSURL fileURLWithPathComponents] - 2
// Create URL for PDF file
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = @"test.pdf";
NSURL *fileURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:documentsDirectory, filename, nil]];

// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL((CFURLRef)fileURL, NULL, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);

// Flip coordinate system
CGRect bounds = CGContextGetClipBoundingBox(pdfContext);
CGContextScaleCTM(pdfContext, 1.0, -1.0);
CGContextTranslateCTM(pdfContext, 0.0, -bounds.size.height);

// Drawing commands
[@"Hello World!" drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:72.0f]];

// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);