UTTypeCreatePreferredIdentifierForTag and CFStringRef in Swift

烈酒焚心 提交于 2021-02-04 17:18:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!