UTTypeCreatePreferredIdentifierForTag and CFStringRef in Swift

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" does not convert to "CFStringRef"

in line

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

any ideas? Thanks

+5
source share
2 answers

UTTypeCreatePreferredIdentifierForTag returns Unmanaged<CFStringRef> , so you need to get the value from the Unmanaged object before you can use it:

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

Please note that I call takeRetainedValue() , since UTTypeCreatePreferredIdentifierForTag returns the object for which we are responsible for the release. Comments on takeRetainedValue() say:

Get the value of this unmanaged link as a managed link and consume its unbalanced persistence.

This is useful when a function returns an unmanaged link and you know that you are responsible for freeing the result.

If you are returning an Unmanaged object back from a function where you are sure you are not responsible for freeing this object, call takeUnretainedValue() .

+15
source

I just want to mention the small module that I posted, which deals with just this kind of thing much better. Your example:

 import SwiftUTI func checkFileExtension(fileURL: URL){ let uti = UTI(withExtension: fileURL.pathExtension) if uti.conforms(to: .image) { print("image") } } 

It is available here: https://github.com/mkeiser/SwiftUTI

0
source

Source: https://habr.com/ru/post/1205797/


All Articles