How to save contact info from vCard into iPhone's Contacts App

10,703

Solution 1

Following is the code for adding user information in iPhone's Contact.

As I told you that i dont know anything about the vCard, but this code posted by malinois in their answer here might be of use:

ABAddressBookRef addressBook = ABAddressBookCreate(); // create address book record 
ABRecordRef person = ABPersonCreate(); // create a person  

NSString *phone = @"0123456789"; // the phone number to add  

//Phone number is a list of phone number, so create a multivalue  
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABPersonPhoneProperty); 
ABMultiValueAddValueAndLabel(phoneNumberMultiValue ,phone,kABPersonPhoneMobileLabel, NULL);

ABRecordSetValue(person, kABPersonFirstNameProperty, @"FirstName" , nil); // first name of the new person 
ABRecordSetValue(person, kABPersonLastNameProperty, @"LastName", nil); // his last name 
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, &anError); // set the phone number property 
ABAddressBookAddRecord(addressBook, person, nil); //add the new person to the record

ABRecordRef group = ABGroupCreate(); //create a group 
ABRecordSetValue(group, kABGroupNameProperty,@"My Group", &error); // set group's name 
ABGroupAddMember(group, person, &error); // add the person to the group         
ABAddressBookAddRecord(addressBook, group, &error); // add the group   

ABAddressBookSave(addressBook, nil); //save the record  

CFRelease(person); // relase the ABRecordRef  variable 

Solution 2

New Contacts Framework introduced with iOS9, saving vCard data into iPhone's contacts is much easier and simpler with Swift4.

import Contacts

    func saveVCardContacts (vCard : Data) { // assuming you have alreade permission to acces contacts

    if #available(iOS 9.0, *) {

        let contactStore = CNContactStore()

        do {

            let saveRequest = CNSaveRequest() // create saveRequests

            let contacts = try CNContactVCardSerialization.contacts(with: vCard) // get contacts array from vCard

            for person in contacts{

                saveRequest.add(person as! CNMutableContact, toContainerWithIdentifier: nil) // add contacts to saveRequest

            }

            try contactStore.execute(saveRequest) // save to contacts

        } catch  {

            print("Unable to show the new contact") // something went wrong

        }

    }else{

        print("CNContact not supported.") //

    }
}

Solution 3

I can't help you for coding, but I have found the common format of vCard in previous post. You can try to achieve your task using this format. The left side values are always static. Hope if you can use that way.

For just reference, i found googling... (support for all 3 mobile platforms)

http://learnyii.blogspot.com/2011/04/vcard-qr-code-iphone-android-blackberry.html

Solution 4


func saveContactsfromVCard(vCard : Data)
    {            
            let contactStore = CNContactStore()

            do {

                let saveRequest = CNSaveRequest() // create saveRequests

                let fetchedContacts = try CNContactVCardSerialization.contacts(with: vCard)

                for person in fetchedContacts{

                   let mutableContact = person.mutableCopy() as! CNMutableContact

                    saveRequest.add(mutableContact, toContainerWithIdentifier: nil)    
                   // saveRequest.add(person, toContainerWithIdentifier: nil) // add contacts to saveRequest

                }

                try contactStore.execute(saveRequest) // save to contacts

                let alert1 = UIAlertController(title: "Successful", message: "Contacts Added Successfully!", preferredStyle: UIAlertController.Style.alert)

                alert1.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler:
                    {(alertAction) in
                }))
                self.present(alert1, animated: true, completion: nil)


            } catch  {

                print("Unable to show the new contact")
        }else{

            print("Contacts not added")

        }
    }
Share:
10,703
Parth Bhatt
Author by

Parth Bhatt

I am iPhone and iPad developer. https://github.com/akashraje/BidirectionalCollectionViewLayout ^[-_,A-Za-z0-9]$ NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"(#[a-zA-Z0-9_-]+)" options:NSRegularExpressionCaseInsensitive error:nil]; NSString *stringData = @"This is Parth known as #parth and this is an awesome place. I am fan of #scganguly."; int count = [reg numberOfMatchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%d",count); if(count>0) { NSArray *array = [reg matchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%@",array); NSMutableArray *stringArray = [[NSMutableArray alloc] init]; for (NSTextCheckingResult *result in array) { NSString *stringFinal = [stringData substringWithRange:result.range]; if(stringFinal != nil) { [stringArray addObject:stringFinal]; } } NSLog(@"stringArray: %@",stringArray); } For @user: @"(@[a-zA-Z0-9_]+)" NSLog(@"Request String: %@", requestString); NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; // NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"url" ofType:@"plist" ]; // NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; // NSString *urlLoc = [fileContents objectForKey:@"baseURL"]; NSString *urlLoc = @"http://portal.abc.com/candidate/post-info"; NSLog(@"URL is %@",urlLoc); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: requestData]; http://blog.stackoverflow.com/archive/ https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/Introduction/Introduction.html http://nscookbook.com/2013/03/ios-programming-recipe-19-using-core-motion-to-access-gyro-and-accelerometer/ http://code4app.net/category/coremotion http://www.devx.com/wireless/Article/44799 upload audio file to php ios Android post request on IOS https://developers.facebook.com/docs/ios/share https://github.com/oliverbarreto/FastFavs/blob/master/TODO2.h

Updated on July 23, 2022

Comments

  • Parth Bhatt
    Parth Bhatt almost 2 years

    In my iPhone app, I want to save the vCards into my iPhone's Contacts when I click onto the vCard which I have.

    How can I do that?

    I have seen an app on app store which does this:

    http://itunes.apple.com/us/app/read-vcard/id402216831?mt=8

    Thanks

  • Parth Bhatt
    Parth Bhatt over 12 years
    Thanks Devang..!! I will look at it.. and I will get back to you soon.. :)
  • Parth Bhatt
    Parth Bhatt over 8 years
    Thank you for the value addition to this post..!!
  • alex
    alex over 8 years
    @yvzzztrk, only for 9.0? i am new to ios app development, but i am developing from ios 8.0. What is 8.0 equivalent for CNContact?
  • yvzzztrk
    yvzzztrk over 8 years
    hi @alex, you can use ABAddressBoook , look at this answer
  • alex
    alex over 8 years
    @yvzzztrk i follow your link and got it to work with your answer. Another question do you have a link how to first show a popup with vcard fields before saving?
  • yvzzztrk
    yvzzztrk over 8 years
    @alex, look at AddressBookUI framework, and ABUnknownPersonViewController
  • alex
    alex over 8 years
    @yvzzztrk thank you! last question when i create it for ios 8 will it work in ios 9 as well?
  • yvzzztrk
    yvzzztrk over 8 years
    @alex, yes of course,but I suggest you to use CNContact framework for iOS 9 with if #available(iOS 9.0, *) { /*code*/ } as in the my answer
  • Abhishek Thapliyal
    Abhishek Thapliyal about 8 years
    can you do this also in objective-c using CNContact
  • Fomentia
    Fomentia over 7 years
    saveRequest.add(person as! CNMutableContact, toContainerWithIdentifier: nil) crashes for me. It says that it "could not cast value of type 'CNContact' (0x1142c85f8) to 'CNMutableContact' (0x1142c7568)". Swift 3, iOS 9.