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
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 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.
Hi I am very new to ios and in my app I am using NSUrlSession for integrating services.
Here my main problem is when I get a response from the server, I can't handle them properly.
When I get a correct response, then see the below json stucture:-
responseObject = {
{
Name = Broad;
DeptNo = A00;
BatchNo = 23;
DeptId = 120;
},
{
Name = James;
DeptNo = B00;
BatchNo = 23;
DeptId = 123;
},
}
when I get a wrong response, see the below json stucture:-
responseObject = {
error = 1;
message = "Invalid Code";
}
when I get a correct response from the server, I am getting an exception in my below if block(like __NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1611c200') and when I get a wrong response then T get exception in my else block
Please help me how to handle them
my code:-
(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
if([MainResponse objectForKey:#"error"] != nil)
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
1)Change Your implementation like below
2)I checked is it dictionary type & error key has some value
3)Earlier you were calling objectForKey on Array, therefore it was crashing
-(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
//here I checked is it dictionary type & error key has some value
if ([MainResponse isKindOfClass:[NSDictionary class ]] &&[MainResponse objectForKey:#"error"])
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
Try this:
//Result Block
typedef void (^ResultBlock)(id, NSError*);
//URL request
-(void)requestURL:(NSURLRequest *)request withResult:(ResultBlock)resultHandler{
//URLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if(!error){
NSError *jsonError = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if([result isKindOfClass:[NSArray class]]){
//Success
resultHandler(result,nil);
}
else if([result isKindOfClass:[NSDictionary class]]){
if([[result objectForKey:#"error"] integerValue]){
//Failure.
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:[result objectForKey:#"message"] forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"Error" code:100 userInfo:errorDetail];
resultHandler(nil, errorDetail);
}
}
}
}];
[task resume];
}
//Call your requestURL method:
[self requestURL:request withResult:^(id result, NSError *error){
if(!error){
//Success, Read & update your list
}
else{
//Error
// NSLog(error.localizedDescription());
}
}];
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]);
}
}
});
});
}
AddressBook api is deprecated in ios 9. I want to load all contacts in an array and display it in a UITableView. I don't want to use iOS default ContactPicker as I have to do some customization while displaying. How to load all contact list in an array for further use?
First I had to check the permission id it is not defined then ask for permission for accessing contacts. Like this:
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusNotDetermined) {
[self.contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
if (granted) {
[self loadUserListFromPhoneBook];
}
}];
}
else if(status == CNAuthorizationStatusAuthorized) {
[self loadUserListFromPhoneBook];
}
After that I had to iterate through the contact list and load all contacts like this:
-(void) loadUserListFromPhoneBookFor
{
NSMutableArray *contacts = [NSMutableArray array];
NSError *error;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [self.contactStore enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(#"error = %#", error);
}
CNContactFormatter *formatter = [[CNContactFormatter alloc] init];
for (CNContact *contact in contacts) {
NSString *string = [formatter stringFromContact:contact];
NSLog(#"contact = %#", string);
}
}
You can use necessary keys for getting more information. Have a look at this for more information. Its has all new contact classes. This video of WWDC helped a lot.