Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTTypeCreatePreferredIdentifierForTag and CFStringRef in Swift

Tags:

swift

ios8

import Foundation
import MobileCoreServices

func checkFileExtension(fileName: NSString){
    println(fileName)

    var fileExtension:CFStringRef = fileName.pathExtension

    println(fileExtension)

    var fileUTI:CFStringRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)

    println(fileUTI)

    let testBool = UTTypeConformsTo(fileUTI, kUTTypeImage) != 0

    if  testBool{
        println("image")
    }
}

I get this error

error : 'Unmanaged' is not convertible to 'CFStringRef'

at line

var fileUTI:CFStringRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)

any ideas ?? Thanks

like image 396
pbeo Avatar asked Oct 29 '14 16:10

pbeo


1 Answers

UTTypeCreatePreferredIdentifierForTag passes back an Unmanaged<CFStringRef>, so you need to get the value out of the Unmanaged object before you can use it:

var unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
var fileUTI = unmanagedFileUTI.takeRetainedValue()

Note that I'm calling takeRetainedValue() since UTTypeCreatePreferredIdentifierForTag is returning an object that we are responsible for releasing. The comments on takeRetainedValue() say:

Get the value of this unmanaged reference as a managed reference and consume an unbalanced retain of it.

This is useful when a function returns an unmanaged reference and you know that you're responsible for releasing the result.

If you get an Unmanaged object back from a function where you are sure you aren't responsible for releasing that object, call takeUnretainedValue() instead.

like image 141
Mike S Avatar answered Feb 07 '23 00:02

Mike S