How to add contact from within an iPhone app? - iphone

I am looking to keep track of people in my iPhone app - either adding them from existing contact data, or prompting the user to enter a new contact which will be saved to their Contacts.
I know I can create a persons record add write it to the Contact book, is it possible to display this screen?
Or do I have to implement my own view to facilitate creating a contact entry?

Apple provides ABNewPersonViewController. If you'd like some sample code, see Quick Contacts, in particular, this section:
ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
picker.newPersonViewDelegate = self;
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
[self presentModalViewController:navigation animated:YES];
[picker release];
[navigation release];

Have you tried using the ABNewPersonViewController?
See this and look for the section titled "Prompting the User to Create a New Person Record".

Below code can use for all IOS version,
#import ,#import
-(void)addContact
{
ABPeoplePickerNavigationController *peoplePicker;
ABAddressBookRef addressBook;
peoplePicker=[[ABPeoplePickerNavigationController alloc] init];
addressBook = [peoplePicker addressBook];
if(!IOS_OLDER_THAN_6)
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
if (![self checkExistsContacts]){
[self addThisContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App does not access to your contacts" message:#"To enable access go to : iPhone's Settings Privacy > Contacts > App > set 'On'" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
// The user has previously given access, add the contact
if (![self checkExistsContacts]){
[self addThisContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App does not access to your contacts" message:#"To enable access go to : iPhone's Settings Privacy > Contacts > App > set 'On'" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
if (![self checkExistsContacts]){
[SVProgressHUD showWithStatus:#"Saving..." maskType:SVProgressHUDMaskTypeClear];
NSString *strCell=#"1-800-123-1234”;
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
NSUInteger addressbookId = 0;
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
ABRecordSetValue(aRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)(strFirstName), &anError);
ABRecordSetValue(aRecord, kABPersonLastNameProperty, (__bridge CFTypeRef)(strLastName), &anError);
//(#"adding phonee");
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
if(strCell) ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)(strCell), kABPersonPhoneIPhoneLabel,NULL);
CFRelease(multi);
ABAddressBookRef addressBook1;
CFErrorRef error = NULL;
addressBook1 = ABAddressBookCreate();
ABAddressBookAddRecord (addressBook1, aRecord, &error);
if (error != NULL) {
}
error = NULL;
if(ABAddressBookSave ( addressBook1, &error)){
addressbookId = ABRecordGetRecordID (aRecord);
}
if (error != NULL) {
}
CFRelease(aRecord);
CFRelease(addressBook1);
[SVProgressHUD dismiss];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
- (void)addThisContact
{
[SVProgressHUD showWithStatus:#"Saving..." maskType:SVProgressHUDMaskTypeClear];
NSString *strCell=#"1-800-123-1234”;
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
ABRecordRef person = ABPersonCreate();
// set name and other string values
CFErrorRef cfError=nil;
if (strFirstName) {
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(strFirstName) , nil);
}
if (strLastName) {
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(strLastName) , nil);
}
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
if (strCell)
{
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFTypeRef)(strCell), (CFStringRef)#"iPhone", NULL);
}
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
CFRelease(phoneNumberMultiValue);
//Add person Object to addressbook Object.
ABAddressBookAddRecord(addressBook, person, &cfError);
if (ABAddressBookSave(addressBook, nil))
{
NSLog(#"\nPerson Saved successfuly");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
NSLog(#"\n Error Saving person to AddressBook");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact details are not available." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
[SVProgressHUD dismiss];
}
- (BOOL)checkExistsContacts
{
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
CFErrorRef err;
ABAddressBookRef adbk = ABAddressBookCreateWithOptions(addressBook,&err);
ABRecordRef moi = NULL;
CFArrayRef matts = ABAddressBookCopyPeopleWithName(adbk, (__bridge CFStringRef)strFirstName);
// might be multiple matts, but let's find the one with last name Neuburg
for (CFIndex ix = 0; ix < CFArrayGetCount(matts); ix++)
{
ABRecordRef matt = CFArrayGetValueAtIndex(matts, ix);
CFStringRef last = ABRecordCopyValue(matt, kABPersonLastNameProperty);
if (last && CFStringCompare(last, (CFStringRef)strLastName, 0) == 0)
moi = matt;
if (last)
CFRelease(last);
}
if (NULL == moi)
{
NSLog(#"Couldn't find myself");
CFRelease(matts);
CFRelease(adbk);
return NO;
}
else
{
NSLog(#"number already exists");
return YES;
}
return NO;
}

Related

SWIFT: CDA to iOS 10 Health app

Is there any way to send a xml file (CDA) to health app from another application? Because my application is getting a xml file from a source and I want to send it directly to the new health app (iOS 10).
Create an HKCDADocumentSample and save it with an HKHealthStore.
First, check for authorization
(void) checkForAuthorization {
if ([HKHealthStore isHealthDataAvailable]) {
NSSet *setRead = [NSSet setWithObjects [HKObjectTypedocumentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
NSSet *setWrite = [NSSet setWithObjects:[HKObjectType documentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
[_store requestAuthorizationToShareTypes:setWrite readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else if (success) {
[self performSelectorOnMainThread:#selector(addDocumentToHealthApp) withObject:nil waitUntilDone:NO];
}
NSLog(#" Success = %#",success? #"YES" : #"NO");
} ];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Health Kit not supported in device." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Second, add Record wmthod this will add a Health record to health app.
(void) addRecordToHealthApp
{
NSURL *cdaPath = [[NSBundle mainBundle] URLForResource:#"sample" withExtension:#"xml"];
NSString*stringPath = [cdaPath absoluteString];
NSData *dataOfCDAFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
NSDate *now = [NSDate date];
int daysToAdd = 7;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSError *err;
HKCDADocumentSample *doc = [HKCDADocumentSample CDADocumentSampleWithData:dataOfCDAFile startDate:[NSDate date] endDate:newDate1 metadata:nil validationError:&err ];
UIAlertView *alert;
if (err) {
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:err.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
[_store saveObject:doc withCompletion:^(BOOL success, NSError * _Nullable error) {
NSLog("Stored %#",success?#"YES":#"NO");
}];
}

MFMessageController crash sometimes

I have the concept of sharing to contacts in my App and used MFMessageComposeViewController.
-(IBAction)btnAddClicked:(id)sender {
#try {
selections = [[NSMutableArray alloc] init];
for(NSIndexPath *indexPath in arSelectedRows) {
NSMutableDictionary *searchable = [[NSMutableDictionary alloc
]init];
[searchable setObject:[[contactsArray objectAtIndex:indexPath.row]objectForKey:#"Phone"]forKey:#"Phone"];
[selections addObject:searchable];
}
if([selections count]>0)
{
NSString *temp1=#"";
for(int i=0;i<[selections count];i++)
{
toRecepients=[[selections objectAtIndex:i]objectForKey:#"Phone"];
temp1=[temp1 stringByAppendingString:toRecepients];
temp1=[temp1 stringByAppendingString:#","];
}
temp1 = [temp1 substringToIndex:[temp1 length]-1];
if(![MFMessageComposeViewController canSendText]) {
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Your device doesn't support SMS!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
return;
}
NSArray *recipents = [temp1 componentsSeparatedByString:#","];
MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
messageController.messageComposeDelegate = self;
messageController.navigationBar.topItem.leftBarButtonItem.title = #"Cancel";
[messageController setRecipients:recipents];
[messageController setBody:self.message];
[self presentModalViewController:messageController animated:YES];
}
else{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Select the contacts you would like to share to" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
return;
}
}
#catch (NSException *exception) {
if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
{
ErrorView *errorView=[[ErrorView alloc]initWithNibName:#"ErrorView" bundle:nil];
if([[[UIDevice currentDevice]systemVersion]floatValue]<5.0)
{
[self presentModalViewController:errorView animated:YES];
}
else
{
[self presentViewController:errorView animated:YES completion:nil];
}
[errorView release];
}
if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) {
ErrorView *errorView=[[ErrorView alloc]initWithNibName:#"ErrorView~iPad" bundle:nil];
if([[[UIDevice currentDevice]systemVersion]floatValue]<5.0)
{
[self presentModalViewController:errorView animated:YES];
}
else
{
[self presentViewController:errorView animated:YES completion:nil];
}
[errorView release];
}
} }
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result {
switch (result) {
case MessageComposeResultCancelled:
{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to send SMS!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
break;
}
case MessageComposeResultFailed:
{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to send SMS!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
break;
}
case MessageComposeResultSent:
{
NSString *messa=[NSString stringWithFormat:#"Shared to %lu contact(s)",(unsigned long)[selections count]];
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Succesful" message:messa delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
break;
}
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
This is the code Im using, which crashes sometimes and displays the error
Assertion failed: (result == KERN_SUCCESS), function +[XPCMachSendRight wrapSendRight:], file /SourceCache/XPCObjects/XPCObjects-46/XPCMachSendRight.m, line 27.
I have put breakpoint to debug, but xcode doesn't showup where the error is produced.
Any ideas/ suggestions would be appreciable..
Enable zombie Objects to find out the line of actual crash.
You can enable Zombie by following steps:
1.Select you project scheme and chose edit scheme.
2.A window will appear, now select diagnostics.
3.Select check mark for enable Zombie objects.
Now run your project.

Issue in Pushing ABPersonViewController

i am having trouble in pushing ABpersonViewController when the name is from user added then everything works perfectly but when name is from default simulator entries then its not working i will explain in detail in code
-(void)showPersonViewController:(NSString *)name
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSString *string = name;
NSLog(#"%#",string);
CFStringRef cfstringRef = (CFStringRef)string;
NSArray *peoplee = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook, cfstringRef);
NSLog(#"%#",peoplee);
// 1ST QUESTION when contact is from defalut contact nslog is null but when from user added then it has value I dont understand why this is happening
if ((peoplee != nil) && [peoplee count])
{
ABRecordRef person = (ABRecordRef)[peoplee objectAtIndex:0];
ABPersonViewController *picker = [[ABPersonViewController alloc] init];
picker.personViewDelegate = self;
picker.displayedPerson = person;
picker.allowsEditing = YES;
[self.navigationController pushViewController:picker animated:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not find Appleseed in the Contacts application"
delegate:nil
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert show];
}
CFRelease(addressBook);
}
I replaced your code of converting NSString To CFStringRef :
This is if you are using ARC:
CFStringRef cfstringRef = (__bridge_retained CFStringRef)string;
But it seems you are not, so for Non ARC:
CFStringRef cfstringRef = (CFStringRef)string;
-(void)showPersonViewController
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSString *string = #"Appleseed";
CFStringRef cfstringRef = (CFStringRef)string;
NSArray *peoplee = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook, cfstringRef);
NSLog(#"%#",peoplee); // does not print null if you have Appleseed as your contact
if ((peoplee != nil) && [peoplee count])
{
ABRecordRef person = (ABRecordRef)[peoplee objectAtIndex:0];
ABPersonViewController *picker = [[ABPersonViewController alloc] init];
picker.personViewDelegate = self;
picker.displayedPerson = person;
// Allow users to edit the person’s information
picker.allowsEditing = YES;
[self.navigationController pushViewController:picker animated:YES];
}
else
{
// Show an alert if "Appleseed" is not in Contacts
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not find Appleseed in the Contacts application"
delegate:nil
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert show];
}
CFRelease(addressBook);
}

Checking Username and Password to match in SQLIte

How can I check if the Username and Password would be the same as the Username and Password in the Database.
AppDelegate.m:
-(void) readLoginFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the Array
lo = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "Select * from Login";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aLoginName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aLoginPass = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aLoginAccess = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new object with the data from the database
Login *los = [[Login alloc] initWithName:aLoginName pass:aLoginPass access:aLoginAccess];
// Add the object to the Array
[lo addObject:los];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
ViewController.m:
-(IBAction)buttonWasClicked:(id)sender
{
if ((userText.text != logins.loginUser) && (passText.text != logins.loginPass))
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Username/Password is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
StudentViewController *studentView = [self.storyboard instantiateViewControllerWithIdentifier:#"studentView"];
[studentView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:studentView animated:YES completion:nil];
}
if (userText.text != logins.loginUser)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Username is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
if (passText.text != logins.loginPass)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Password is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Even when the Username and Password I type is exactly the same as in the database, it would still show me the error message instead of displaying the next view.
You have to check NSStrings in objective-c with
isEqualToString
For your example:
if (![userText.text isEqualToString:logins.loginUser])
Check: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/isEqualToString:
You can use isEqualToString method to check that two string is equal....
if ([userText.text isEqualToString:logins.loginUser])
and apply condition like this
-(IBAction)buttonWasClicked:(id)sender
{
Login *logins = nil;
logins= [lo objectAtIndexPath:0];
if ([userText.text isEqualToString:logins.loginUser] && [passText.text isEqualToString:logins.loginPass])
{
StudentViewController *studentView = [self.storyboard instantiateViewControllerWithIdentifier:#"studentView"];
[studentView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:studentView animated:YES completion:nil];
}
else if (![userText.text isEqualToString:logins.loginUser])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Username is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else if (![passText.text isEqualToString:logins.loginPass])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Password is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[[NSString alloc] initWithFormat:#"Your Username/Password is incorrect!"] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}

How to edit the existing contacts programmatically in iPhone

I want to edit the contact list programatically.is there any API's available for this.....
-(void)showPersonViewController:(NSString *)nameInContact
{
// Fetch the address book
ABAddressBookRef addressBook = ABAddressBookCreate();
// Search for the person in the address book
NSArray *people = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook, CFSTR(nameInContact));
// Display the information if found in the address book
if ((people != nil) && [people count])
{
ABRecordRef person = (ABRecordRef)[people objectAtIndex:0];
ABPersonViewController *picker = [[[ABPersonViewController alloc] init] autorelease];
picker.personViewDelegate = self;
picker.displayedPerson = person;
// Allow users to edit the person’s information
picker.allowsEditing = YES;
[self.navigationController pushViewController:picker animated:YES];
}
else
{
// Show an alert if the person is not in Contacts
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Could not find %# in the Contacts application", nameInContact]
delegate:nil
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert show];
[alert release];
}
[people release];
CFRelease(addressBook);
}
You can access the contacts programmatically and edit them using ABAddressBook.framework.
You can find documentation here:
http://developer.apple.com/library/mac/#documentation/userexperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html
and programming guide here:
http://developer.apple.com/library/ios/#documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Introduction.html