How to add multiple phone number using Contact Framework iOS 9
CNMutableContact *contact = [test mutableCopy];
CNLabeledValue *homePhone_1 = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:#"019312-555-1212"]];
CNLabeledValue * homePhone_2 = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:#"312-555-1219"]];
[contact.phoneNumbers addObjectsFromArray:#[homePhone_1]];
[contact.phoneNumbers addObjectsFromArray:#[homePhone_2]];
CNSaveRequest *request = [[CNSaveRequest alloc] init];
[request updateContact:contact];
Please help guys. This is not working.
Please try with following code.
- (void) addContact {
CNMutableContact * contact = [CNMutableContact new];
contact.middleName = #"Testmiddle";
contact.contactType = CNContactTypePerson;
contact.givenName = #"TestGivenname";
contact.familyName = #"Taken";
CNLabeledValue *homePhone_1 = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:#"019312-555-1212"]];
CNLabeledValue * homePhone_2 = [CNLabeledValue labeledValueWithLabel:CNLabelWork value:[CNPhoneNumber phoneNumberWithStringValue:#"312-555-1219"]];
contact.phoneNumbers = #[homePhone_1, homePhone_2];
CNSaveRequest *request = [[CNSaveRequest alloc] init];
[request addContact:contact toContainerWithIdentifier:nil];
#try {
CNContactStore * store = [CNContactStore new];
[store executeSaveRequest:request error:nil];
}
#catch (NSException *exception) {
NSLog(#"description = %#",[exception description]);
}
}
For update contact you need to use following code.
Fetching contact encapsulate I/O operation so that why i recommended that you use them on background threads. If needed, you can safely send immutable fetch results back to the main thread
- (void)updateContact {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
CNContactStore * store = [CNContactStore new];
NSArray * arrFetchedcontact = [NSArray array];
#try {
arrFetchedcontact = [store unifiedContactsMatchingPredicate:[CNContact predicateForContactsMatchingName:#"TestGivenname"] keysToFetch:[NSArray arrayWithObjects:#"CNContactGivenNameKey",#"CNContactFamilyNameKey",CNContactPhoneNumbersKey, nil] error:nil];
}
#catch (NSException *exception) {
NSLog(#"description = %#",[exception description]);
}
dispatch_async(dispatch_get_main_queue(), ^{
if([arrFetchedcontact count] > 0){
CNMutableContact * contact = [[arrFetchedcontact objectAtIndex:0] mutableCopy];
NSMutableArray * arrNumbers = [[contact phoneNumbers] mutableCopy];
CNLabeledValue * homePhone_2 = [CNLabeledValue labeledValueWithLabel:CNLabelOther value:[CNPhoneNumber phoneNumberWithStringValue:#"33333333333"]];
[arrNumbers addObject:homePhone_2];
contact.phoneNumbers = arrNumbers;
CNSaveRequest *request = [[CNSaveRequest alloc] init];
[request updateContact:contact];
#try {
[store executeSaveRequest:request error:nil];
}
#catch (NSException *exception) {
NSLog(#"description = %#",[exception description]);
}
}
});
});
}
Related
Fetching contact list using CNContactStore and converting complete contact list to VCard, all are coming fine except i am not getting contact image and notes.
NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
});
return;
}
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(#"error = %#", fetchError);
}
for (CNContact *contact in contacts) {
CNContact *contact1 = contact.mutableCopy;
[contactsArray addObject:contact1];
}
NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
NSLog(#"vcardStr = %#",vcardStr);
}];
Contact Profile images from CNContact
if (granted == YES) {
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *Contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error)
{
//error
}
else
{
for (CNContact *contact in Contacts)
{
UIImage *contactProfileImage;
if (contact.imageDataAvailable)
{
UIImage * image = [UIImage imageWithData:contact.imageData];
contactProfileImage = image;
}
else
{
contactProfileImage = [UIImage imageNamed:#"icon.png"];
}
}
I am trying to import vcf file in my contacts.When First time I save a contact it imported successfully, no problem.But when I am trying to update that same contact it's doing nothing.What I want? I want if I will update contact then phone numbers add in exist contact.I am using CNContact.
to save contacts:
-(void)saveVCardContacts:(CNContact *)contact{
NSError * error;
CNSaveRequest *saveRequest = [[CNSaveRequest alloc]init];
[saveRequest addContact:[contact mutableCopy] toContainerWithIdentifier:nil];
BOOL success = [self.store executeSaveRequest:saveRequest error:&error];
if(success)
NSLog(#"import successfully");
else
NSLog(#"Error = %#",error);
}
to update
-(void)updateVCardContacts:(CNContact *)contact{
NSError *error;
CNSaveRequest *saveRequest = [[CNSaveRequest alloc]init];
[saveRequest updateContact:[contact mutableCopy]];
BOOL success = [self.store executeSaveRequest:saveRequest error:&error];
if(success)
NSLog(#"update successfully");
else
NSLog(#"Error = %#",error);
}
You can replace your number with only names
CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
CNContactStore * store = [[CNContactStore alloc]init];
NSArray* arrFetchedcontact = nil;
#try {
NSError * err = nil;
NSArray * keytoFetch = #[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];
NSPredicate * predicate = [CNContact predicateForContactsMatchingName:GivenNames];
arrFetchedcontact = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keytoFetch error:&err];
}
#catch (NSException *exception) {
NSLog(#"description = %#",[exception description]);
}
if([arrFetchedcontact count] > 0)
{
NSLog(#"ArrFetchedContact %#",arrFetchedcontact);
CNMutableContact * contactToUpdate = [[arrFetchedcontact objectAtIndex:0] mutableCopy];
NSMutableArray * arrNumbers = [[contactToUpdate phoneNumbers] mutableCopy];
[arrNumbers removeObjectAtIndex:0];
CNLabeledValue * homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:FieldNumbers]];
NSLog(#"Print Homephone %#",homePhone);
[arrNumbers addObject:homePhone];
[contactToUpdate setPhoneNumbers:arrNumbers];
[saveRequest updateContact:contactToUpdate];
#try {
NSLog(#"Success %d",[store executeSaveRequest:saveRequest error:nil]);
}
#catch (NSException *exception) {
NSLog(#"description = %#",[exception description]);
}
}
Field number is the number you want to replace with given name
Given name is the name for the person with that number
i need to fetch all contacts from device and want to show individually accordingly ..kindly have a look my code thanks
// using method to fetch contacts from device
-(void)fetchContacts{
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if( status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted){
NSLog(#"access denied");
}else{
CNContactStore *contactStore = [[CNContactStore alloc] init];
NSArray *keys = [[NSArray alloc]initWithObjects:CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, CNContactViewController.descriptorForRequiredKeys, nil];
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
request.predicate = nil;
[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop){
NSString *phoneNumber = #"";
if( contact.phoneNumbers)
phoneNumber = [[[contact.phoneNumbers firstObject] value] stringValue];
NSMutableDictionary *contactValue=[[NSMutableDictionary alloc] init];
if ([contact.givenName isEqualToString:#""]) {
}else{
[contactValue setValue:phoneNumber forKey:#"phoneNumber"];
[contactValue setObject:contact.givenName forKey:#"userName"];
[contactValue setObject:contact.familyName forKey:#"familyName"];
[contactValue setObject:[contact.emailAddresses valueForKey:#"value"] ?:#"" forKey:#"emailAddress"];
[contactValue setObject:contact.identifier forKey:#"phoneIdentifier"];
}
[_totalContact addObject:contactValue];
}];
}
You can use Contacts framework for that.
CNContactStore *cnContactStore = [[CNContactStore alloc] init];
[cnContactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = cnContactStore.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
_contactDetailArray = [cnContactStore unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#”error fetching contacts %#”, error);
} else {
//Do Something
}
}
}];
For Complete code please visit my blog
I am using this code to export contact from ios phonebook to .vcf file. I have used this code for the task. But vcardString is always returning nil. Please help me to solve this issue.
NSMutableArray *contacts=[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
});
return;
}
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(#"error = %#", fetchError);
}
// you can now do something with the list of contacts, for example, to show the names
CNContactFormatter *formatter = [[CNContactFormatter alloc] init];
for (CNContact *contact in contacts) {
[contactsArray addObject:contact];
// NSString *string = [formatter stringFromContact:contact];
//NSLog(#"contact = %#", string);
}
//NSError *error;
NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
NSLog(#"vcardString = %#",vcardString);
}];
Change this line:
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[[CNContactVCardSerialization descriptorForRequiredKeys]]
This fetches all required info for creating a vCard.
This is the code in my detail view it can delete event in when u come to detail view press the switch to add event and then press it again to delete it. However, when u come to detail view and then press back (using navigation) and then come o the same page again it cannot delete the event please help
there are more function but I delete just focus on Switch and EVENTKIT
//
// DetailScheduleViewController.m
// Register
//
// Created by junejubu on 3/10/2558 BE.
// Copyright (c) 2558 Thananont Aunsiripant. All rights reserved.
//
- (void)viewDidLoad {
[super viewDidLoad];
//NSLog(#"check show id sch ::%#",self.Show_ID);
self.Switch.on = NO;
self.lblNotification.text = #"Notification OFF";
[self getUserNotification];
[self getUserFollow];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getUserNotification
{
NSString *urlStr2 = #"http://ptvshowthai.com/getNotification.php";
NSURL *url2 = [NSURL URLWithString:urlStr2];
self.getnoti = [ASIFormDataRequest requestWithURL:url2];
self.getnoti.requestMethod = #"POST"; //DELETE, PUT
self.getnoti.delegate = self;
self.getnoti.timeOutSeconds = 30;
[self.getnoti setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.getnoti setValidatesSecureCertificate:NO];
[self.getnoti startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"requestFinished");
if (request == self.getnoti) {
self.dictnoti = [NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingAllowFragments error:nil];
self.NOTI = [[NSMutableArray alloc] init];
for (NSDictionary *dataDic in self.dictnoti )
{
// unsigned long count2 = [self.dict2 count];
NSString *ShowID2 = [dataDic objectForKey:#"Show_ID"];
self.str2 = [dataDic objectForKey:#"Event_Store"];
// NSLog(#"check str2 :: %#",self.str2);
[self.NOTI addObject:ShowID2];
}
NSLog(#"Show who noti ::%#",self.NOTI);
// NSLog(#"check str2 :: %#",self.str2);
}
if(request ==self.getFollow){
self.dict2 = [NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Dict getFollow :: %#",self.dict2);
//unsigned long count2 = [self.dict2 count];
//NSLog(#"show count ::%lu",count2);
_Show = [[NSMutableArray alloc] init];
// NSDictionary *dict;
for (NSDictionary *dataDic in self.dict2 )
{
// unsigned long count2 = [self.dict2 count];
NSString *ShowID = [dataDic objectForKey:#"Show_ID"];
[self.Show addObject:ShowID];
}
if ([self.Show containsObject: self.Show_ID]) {
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
_i = #"0";
NSLog(#"check i green :: %#",_i);
self.Switch.hidden = NO;
NSLog(#"check self.noti : %#",self.NOTI);
if ([self.NOTI containsObject: self.Show_ID]){
self.Switch.on = YES;
}
self.lblNotification.hidden = NO;
[self.Switch addTarget:self action:#selector(Onoff) forControlEvents:UIControlEventValueChanged];
}
else{
_lblFollow.text = #"Follow";
_lblFollow.textColor = [UIColor redColor];
_i = #"1";
NSLog(#"check i red :: %#",_i);
self.Switch.hidden = YES;
self.Switch.on = NO;
self.lblNotification.hidden = YES;
[self.Switch addTarget:self action:#selector(Onoff) forControlEvents:UIControlEventValueChanged];
}
}
}
-(void)addevent{
_eventStore = [[EKEventStore alloc] init];
if ([_eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
[_eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
addEventgranted = 1;
EKEvent *event = [EKEvent eventWithEventStore:_eventStore];
[event setTitle:self.showNameTitle];
[event setStartDate: self.today];
[event setEndDate:[[NSDate alloc]initWithTimeInterval:self.duration sinceDate:event.startDate]];
NSTimeInterval alarmOffset = -300;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:alarmOffset];
[event addAlarm:alarm];
[event setCalendar:[_eventStore defaultCalendarForNewEvents]];
NSError *err;
[_eventStore saveEvent:event span:EKSpanThisEvent error:&err];
self.str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
NSLog(#"check self.str :: %#",self.str);
NSString *url = #"http://ptvshowthai.com/insertNotification.php";
NSURL *urls = [NSURL URLWithString:url];
self.formData = [ASIFormDataRequest requestWithURL:urls];
self.formData.requestMethod = #"POST";
self.formData.delegate = self;
self.formData.timeOutSeconds = 30;
[self.formData setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.formData setPostValue: self.Show_ID forKey:#"showID"];
NSLog(#"check str::: %#",self.str);
[self.formData setPostValue: self.str forKey:#"event"];
[self.formData setValidatesSecureCertificate:NO];
[self.formData startAsynchronous];
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
NSLog(#"Follow");
[self getUserNotification];
}
}];
}
}
-(void)alert
{
if (addEventgranted == 1) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Event Successfully added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
-(void)Onoff
{
if (self.Switch.on) {
[self addevent];
[self performSelector:#selector(alert) withObject:nil afterDelay:0.3];
self.lblNotification.text =#"Notification On";
}
else
{
NSLog(#"check str22::%#",self.str2);
EKEvent* event2 = [_eventStore eventWithIdentifier:self.str2];
if (event2 != nil) {
NSError* error = nil;
[_eventStore removeEvent:event2 span:EKSpanThisEvent error:&error];
}
self.lblNotification.text =#"Notification OFF";
NSString *url = #"http://ptvshowthai.com/deleteNotification.php";
NSURL *urls = [NSURL URLWithString:url];
self.formData = [ASIFormDataRequest requestWithURL:urls];
self.formData.requestMethod = #"POST";
self.formData.delegate = self;
self.formData.timeOutSeconds = 30;
[self.formData setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.formData setPostValue: self.Show_ID forKey:#"showID"];
[self.formData setValidatesSecureCertificate:NO];
[self.formData startAsynchronous];
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
NSLog(#"Follow");
[self getUserNotification];
}
}
Add below line of code at switch off condition also
Its better to add below line at ViewDidLoad instead of addEvent method..
_eventStore = [[EKEventStore alloc] init];
Hope it fixes..!