1

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!!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

yes, but ho obtain pàth file://... 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];
How convert this line, to save in the path ? [self.fileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:self]; I can't call delegate
Does your class implement the protocol? It would be a lot better to make another question with the specific line, what you tried, and the exact error message you are getting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.