I don't understand why my code doesn't compile with Swift.
I am trying to convert this Objective-C code:
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(@"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
}
This is my current rendition in Swift:
var error:CFErrorRef
var addressBook = ABAddressBookCreateWithOptions(nil, nil);
if (addressBook != nil) {
println("Succesful.");
var allContacts:CFArrayRef = ABAddressBookCopyArrayOfAllPeople(addressBook);
}
but, Xcode reports:
'Unmanaged' is not convertible to 'CFArrayRef'
Do you guys have an idea ?
Obviously, if targeting iOS version 9 or greater, you shouldn't use the
AddressBook
framework at all, and instead use theContacts
framework instead.So,
Import
Contacts
:Make sure to supply a
NSContactsUsageDescription
in yourInfo.plist
.Then, you can then access contacts. E.g. in Swift 3:
Where
My original answer for AddressBook framework is below.
A couple of observations:
If you want to use
error
parameter ofABAddressBookCreateWithOptions
, define it to beUnmanaged<CFError>?
.If it fails, take a look at the error object (doing
takeRetainedValue
so you don't leak).Make sure to
takeRetainedValue
of the address book, too, so you don't leak.You probably shouldn't just grab the contacts, but you probably should request permission first.
Pulling that all together you get: