问题
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
回答1:
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.
回答2:
I just want to mention a little module I published that deals exactly with this kind of thing in a much nicer way. Your example would become:
import SwiftUTI
func checkFileExtension(fileURL: URL){
let uti = UTI(withExtension: fileURL.pathExtension)
if uti.conforms(to: .image) {
print("image")
}
}
It's available here: https://github.com/mkeiser/SwiftUTI
来源:https://stackoverflow.com/questions/26635643/uttypecreatepreferredidentifierfortag-and-cfstringref-in-swift