Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing temp directory in Swift

I was trying to access temp directory in Swift. In Objective-C, I could use the following code to do so:

- (NSString *)tempDirectory {

    NSString *tempDirectoryTemplate =
    [NSTemporaryDirectory() stringByAppendingPathComponent:@"XXXXX"];
    const char *tempDirectoryTemplateCString = [tempDirectoryTemplate fileSystemRepresentation];
    char *tempDirectoryNameCString           = (char *)malloc(strlen(tempDirectoryTemplateCString) + 1);
    strcpy(tempDirectoryNameCString, tempDirectoryTemplateCString);
    char *result                             = mkdtemp(tempDirectoryNameCString);
    if (!result) {
        return nil;
    }
    NSString *tempDirectoryPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:tempDirectoryNameCString length:strlen(result)];
    free(tempDirectoryNameCString);
    return tempDirectoryPath;
}

However, I'm a bit confuse about the type conversion and casting from Objective-C to Swift, such as const char * or CMutablePointer<CChar>. Is there any documents that I should look into?

Thanks.

like image 767
Cai Avatar asked Jun 18 '14 09:06

Cai


2 Answers

How about something like :

public extension FileManager {
    func createTempDirectory() throws -> String {
        let tempDirectory = (NSTemporaryDirectory() as NSString).appendingPathComponent(UUID().uuidString)
        try FileManager.default.createDirectory(atPath: tempDirectory,
                                                withIntermediateDirectories: true,
                                                attributes: nil)
        return tempDirectory
    }
}

It doesn't answer your question about char* but it's cleaner...

NSFileManager reference here.

Also check out this SO question regarding unique names.

like image 108
Grimxn Avatar answered Oct 06 '22 09:10

Grimxn


According to Apple, use of NSTemporaryDirectory is discouraged:

See the FileManager method url(for:in:appropriateFor:create:) for the preferred means of finding the correct temporary directory. For more information about temporary files, see File System Programming Guide.

So instead, you should use FileManager.default.temporaryDirectory

or if you want an unique path:

let extractionPath = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)

like image 44
Antzi Avatar answered Oct 06 '22 08:10

Antzi