Skip to content

Instantly share code, notes, and snippets.

@Eridana
Last active October 29, 2015 09:02
Show Gist options
  • Save Eridana/5285c2bcdba69f2f30bc to your computer and use it in GitHub Desktop.
Save Eridana/5285c2bcdba69f2f30bc to your computer and use it in GitHub Desktop.
get CNContacts from Contacts.framework (objective-c)
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 80000
//ios 9+
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
NSMutableArray *contacts = [NSMutableArray new];
NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(@"error fetching contacts %@", error);
} else {
for (CNContact *contact in cnContacts) {
for (CNLabeledValue *label in contact.phoneNumbers) {
if ([[label.value stringValue] length] == 0) {
continue;
}
Contact *newContact = [[Contact alloc] init];
newContact.phone = [label.value stringValue];
newContact.firstName = contact.givenName;
newContact.lastName = contact.familyName;
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image == nil) {
image = [UIImage imageNamed:@"noImageContact"];
}
else {
image = [self resizeImage:image toWidth:25];
}
newContact.image = image;
[contacts addObject:newContact];
}
}
}
[self showCNContactsView];
}
}];
#else
//ios 8-
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
});
#endif
#pragma mark - Image Resize
- (UIImage *)resizeImage:(UIImage *)image toWidth:(CGFloat)width
{
CGSize newSize = CGSizeMake(width, width);
CGFloat widthRatio = newSize.width/image.size.width;
CGFloat heightRatio = newSize.height/image.size.height;
if(widthRatio > heightRatio) {
newSize = CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
}
else {
newSize = CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment