How to convert unmanaged to NSData?

后端 未结 2 1567
终归单人心
终归单人心 2021-01-12 19:06

I need to convert my Objective-C to Swift to get an image of a contact from the Address Book. But I get an error with for cast from CFData to NSData

相关标签:
2条回答
  • 2021-01-12 19:34
    if let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize)?.takeUnretainedValue() {
       if let image = UIImage(data: imgData) {
          //Here's your UIImage
       }
    }
    
    0 讨论(0)
  • 2021-01-12 19:39

    As explained in Working with Cocoa Data Types, you have to convert the unmanaged object to a memory managed object with takeUnretainedValue() or takeRetainedValue(). In your case

    if (ABPersonHasImageData(person)) {
        let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue()
        let image = UIImage(data: imgData)
    }
    

    because ABPersonCopyImageDataWithFormat() returns a (+1) retained value.

    0 讨论(0)
提交回复
热议问题