user3745888
user3745888

Reputation: 6253

How to use the file path API from Swift to get documents directory and create filenames

I have this code to record video with AVFoundation but I don't know how convert to Swift

- (void)startRecording 
{    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
    NSString* dateTimePrefix = [formatter stringFromDate:[NSDate date]];

    int fileNamePostfix = 0;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = nil;
    do
        filePath =[NSString stringWithFormat:@"/%@/%@-%i.mp4", documentsDirectory, dateTimePrefix, fileNamePostfix++];
    while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

    NSURL *fileURL = [NSURL URLWithString:[@"file://" stringByAppendingString:filePath]];
    [self.fileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:self];
}

I don't know how work with this paths in Swift..

Thanks!!

Upvotes: 1

Views: 5015

Answers (1)

Lou Franco
Lou Franco

Reputation: 89162

Here's how you get the document directory

// NSArray *paths = NSSearchPathForDirectoriesInDomains(
//   NSDocumentDirectory, NSUserDomainMask, YES);
let paths = NSSearchPathForDirectoriesInDomains(
      .DocumentDirectory, .UserDomainMask, true)

// NSString *documentsDirectory = [paths objectAtIndex:0];
let documentsDirectory = paths[0] as String

Here's how you do the filename picking with the postfix

var filePath:String? = nil
var fileNamePostfix = 0
do {
    // filePath =[NSString stringWithFormat:@"/%@/%@-%i.mp4", 
    //   documentsDirectory, dateTimePrefix, fileNamePostfix++];
    filePath = 
       "\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix++).mp4"
} while (NSFileManager.defaultManager().fileExistsAtPath(filePath))

This code is just a straight port of your code, except that I removed the / before documentsDirectory because it is already an absolute path.

Upvotes: 4

Related Questions