Accessing temp directory in Swift

前端 未结 6 2250
死守一世寂寞
死守一世寂寞 2020-12-18 02:13

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

- (NSString *)tempDirectory {

    NSString *tempDir         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 02:49

    A direct translation of your Objective-C code to Swift would be:

    func tempDirectory()->String! {
        let tempDirectoryTemplate = NSTemporaryDirectory()  + "XXXXX"
        var tempDirectoryTemplateCString = tempDirectoryTemplate.fileSystemRepresentation().copy()
        let result : CString = reinterpretCast(mkdtemp(&tempDirectoryTemplateCString))
        if !result {
            return nil
        }
        let fm = NSFileManager.defaultManager()
        let tempDirectoryPath = fm.stringWithFileSystemRepresentation(result, length: Int(strlen(result)))
        return tempDirectoryPath
    }
    

    It uses the same mkdtemp() BSD method as your original code. This method creates a directory name from the template which is guaranteed not to exist at the time where the method is called.

    Thanks to Nate Cook who figured out that reinterpretCast() can be used to treat the UnsafePointer returned by mkdtemp() as a CString, so that it can be passed to stringWithFileSystemRepresentation(), see Working with C strings in Swift, or: How to convert UnsafePointer to CString.


    As of Xcode 6 beta 6, the reinterpretCast() is not necessary anymore and the above code can be simplified to

    func tempDirectory()->String! {
        let tempDirectoryTemplate = NSTemporaryDirectory()  + "XXXXX"
        var tempDirectoryTemplateCString = tempDirectoryTemplate.fileSystemRepresentation()
        let result = mkdtemp(&tempDirectoryTemplateCString)
        if result == nil {
            return nil
        }
        let fm = NSFileManager.defaultManager()
        let tempDirectoryPath = fm.stringWithFileSystemRepresentation(result, length: Int(strlen(result)))
        return tempDirectoryPath
    }
    

提交回复
热议问题