5

I learned this from iOS tutorial, but it doesn't work

func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
    var mediaType = info.objectForKey(UIImagePickerControllerMediaType) as String
    var originalImage, editedImage, imageToUse: UIImage

    // Handle a still image picked from a photo album
    if (CFStringCompare(CFStringRef(mediaType), kUTTypeImage, 0) == CFComparisonResult.CompareEqualTo) {
        editedImage = info.objectForKey(UIImagePickerControllerEditedImage) as UIImage
        originalImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage

        if (editedImage) {
            imageToUse = editedImage
        } else {
            imageToUse = originalImage
        }

        // Do something with imageToUse
    }

It constantly alerts me

CFStringRef is not constructible with '@lvalue String'

So I tried this:

// Handle a still image picked from a photo album
    var temp = mediaType as CFString
    if (CFStringCompare(temp, kUTTypeImage, 0) == CFComparisonResult.CompareEqualTo) {
        editedImage = info.objectForKey(UIImagePickerControllerEditedImage) as UIImage
        originalImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage

And it alerts me with

Cannot convert the expression's type 'CFString' to type '$T1'

2 Answers 2

7

Swift.String and NSString bridge automatically, and NSString and CFString can be cast to one another, but you can't (for now?) transitively get all the way from a Swift String to a CFString without an extra cast or two.

Here's a Swift string, a function that takes a CFString, and how to call it by casting to NSString:

var str = "Hello, playground"

func takesCFString(s: CFString) {}

takesCFString(str as NSString)

Note you don't need to use CFStringRefin Swift (and most of the Swift declarations of CFString API don't). The compiler takes advantage of the automatic ARC bridging for CF types that was introduced with Xcode 5 to let you treat those types like Swift (or ObjC) objects.

Sign up to request clarification or add additional context in comments.

Comments

2
var str = "string"
var cfstr:CFString = str as NSString // OR str.__conversion()

1 Comment

Error when using this method: "'NSString is not a subtype of 'CFstring'". However, the commented portion appears to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.