How to convert unmanaged to NSData?

2020-04-05 08:12发布

问题:

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 and I don't know how make this work. What can I do to make this work correctly?

In Objective-C:

ABRecordID contactID = ABRecordGetRecordID(contactRef);
ABAddressBookRef addressBook = ABAddressBookCreate();

ABRecordRef origContactRef = ABAddressBookGetPersonWithRecordID(addressBook, contactID);

if (ABPersonHasImageData(origContactRef)) {
    NSData *imgData = (NSData*)ABPersonCopyImageDataWithFormat(origContactRef, kABPersonImageFormatOriginalSize);
    img = [UIImage imageWithData: imgData]; 

    [imgData release];
}

CFRelease(addressBook);

return img;

In Swift:

var image: UIImage!

if ABPersonHasImageData(person) {
    var imgData = (ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize))
    image = UIImage.imageWithData(imgData) //Here get the error 
}

回答1:

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.



回答2:

if let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize)?.takeUnretainedValue() {
   if let image = UIImage(data: imgData) {
      //Here's your UIImage
   }
}


标签: swift xcode6