-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRCTAddressBook.m
297 lines (255 loc) · 10.8 KB
/
RCTAddressBook.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
@import AddressBook;
#import <UIKit/UIKit.h>
#import "RCTAddressBook.h"
@implementation RCTAddressBook
RCT_EXPORT_MODULE();
- (NSDictionary *)constantsToExport
{
return @{
@"PERMISSION_DENIED": @"denied",
@"PERMISSION_AUTHORIZED": @"authorized",
@"PERMISSION_UNDEFINED": @"undefined"
};
}
RCT_EXPORT_METHOD(checkPermission:(RCTResponseSenderBlock) callback)
{
int authStatus = ABAddressBookGetAuthorizationStatus();
if ( authStatus == kABAuthorizationStatusDenied || authStatus == kABAuthorizationStatusRestricted){
callback(@[[NSNull null], @"denied"]);
} else if (authStatus == kABAuthorizationStatusAuthorized){
callback(@[[NSNull null], @"authorized"]);
} else { //ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined
callback(@[[NSNull null], @"undefined"]);
}
}
RCT_EXPORT_METHOD(requestPermission:(RCTResponseSenderBlock) callback)
{
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (!granted){
[self checkPermission:callback];
return;
}
[self checkPermission:callback];
});
}
RCT_EXPORT_METHOD(getContacts:(RCTResponseSenderBlock) callback)
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
int authStatus = ABAddressBookGetAuthorizationStatus();
if(authStatus != kABAuthorizationStatusAuthorized){
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if(granted){
[self retrieveContactsFromAddressBook:addressBookRef withCallback:callback];
}else{
NSDictionary *error = @{
@"type": @"permissionDenied"
};
callback(@[error, [NSNull null]]);
}
});
}
else{
[self retrieveContactsFromAddressBook:addressBookRef withCallback:callback];
}
}
-(void) retrieveContactsFromAddressBook:(ABAddressBookRef)addressBookRef
withCallback:(RCTResponseSenderBlock) callback
{
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBookRef, NULL, kABPersonSortByLastName);
int totalContacts = (int)[allContacts count];
int currentIndex = 0;
int maxIndex = --totalContacts;
NSMutableArray *contacts = [[NSMutableArray alloc] init];
while (currentIndex <= maxIndex){
NSDictionary *contact = [self dictionaryRepresentationForABPerson: (ABRecordRef)[allContacts objectAtIndex:(long)currentIndex]];
if(contact){
[contacts addObject:contact];
}
currentIndex++;
}
callback(@[[NSNull null], contacts]);
}
-(NSDictionary*) dictionaryRepresentationForABPerson:(ABRecordRef) person
{
NSMutableDictionary* contact = [NSMutableDictionary dictionary];
NSNumber *recordID = [NSNumber numberWithInteger:(ABRecordGetRecordID(person))];
NSString *firstName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *middleName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonMiddleNameProperty));
[contact setObject: recordID forKey: @"recordID"];
BOOL hasName = false;
if (firstName) {
[contact setObject: firstName forKey:@"firstName"];
hasName = true;
}
if (lastName) {
[contact setObject: lastName forKey:@"lastName"];
hasName = true;
}
if(middleName){
[contact setObject: (middleName) ? middleName : @"" forKey:@"middleName"];
}
if(!hasName){
//nameless contact, do not include in results
return nil;
}
//handle phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
CFStringRef phoneLabelRef = ABMultiValueCopyLabelAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge_transfer NSString *) phoneNumberRef;
NSString *phoneLabel = (__bridge_transfer NSString *) ABAddressBookCopyLocalizedLabel(phoneLabelRef);
if(phoneNumberRef){
CFRelease(phoneNumberRef);
}
if(phoneLabelRef){
CFRelease(phoneLabelRef);
}
NSMutableDictionary* phone = [NSMutableDictionary dictionary];
[phone setObject: phoneNumber forKey:@"number"];
[phone setObject: phoneLabel forKey:@"label"];
[phoneNumbers addObject:phone];
}
[contact setObject: phoneNumbers forKey:@"phoneNumbers"];
//end phone numbers
//handle emails
NSMutableArray *emailAddreses = [[NSMutableArray alloc] init];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiEmails);i++) {
CFStringRef emailAddressRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
CFStringRef emailLabelRef = ABMultiValueCopyLabelAtIndex(multiEmails, i);
NSString *emailAddress = (__bridge_transfer NSString *) emailAddressRef;
NSString *emailLabel = (__bridge_transfer NSString *) ABAddressBookCopyLocalizedLabel(emailLabelRef);
if(emailAddressRef){
CFRelease(emailAddressRef);
}
if(emailLabelRef){
CFRelease(emailLabelRef);
}
NSMutableDictionary* email = [NSMutableDictionary dictionary];
[email setObject: emailAddress forKey:@"email"];
[email setObject: emailLabel forKey:@"label"];
[emailAddreses addObject:email];
}
//end emails
[contact setObject: emailAddreses forKey:@"emailAddresses"];
[contact setObject: [self getABPersonThumbnailFilepath:person] forKey:@"thumbnailPath"];
return contact;
}
-(NSString *) getABPersonThumbnailFilepath:(ABRecordRef) person
{
if (ABPersonHasImageData(person)){
NSArray *linkedPersons = CFBridgingRelease(ABPersonCopyArrayOfAllLinkedPeople(person));
for (id obj in linkedPersons) {
ABRecordRef aLinkedPerson = (__bridge ABRecordRef)obj;
if (aLinkedPerson == person) {
continue; // skip the original one
}
if (ABPersonHasImageData(aLinkedPerson)) {
person = aLinkedPerson;
break;
}
}
CFDataRef photoDataRef = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
if(!photoDataRef){
return @"";
}
NSData* data = (__bridge_transfer NSData*)photoDataRef;
NSString* tempPath = [NSTemporaryDirectory()stringByStandardizingPath];
NSError* err = nil;
NSString* tempfilePath = [NSString stringWithFormat:@"%@/thumbimage_XXXXX", tempPath];
char template[tempfilePath.length + 1];
strcpy(template, [tempfilePath cStringUsingEncoding:NSASCIIStringEncoding]);
mkstemp(template);
tempfilePath = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:template
length:strlen(template)];
[data writeToFile:tempfilePath options:NSAtomicWrite error:&err];
CFRelease(photoDataRef);
if(!err){
return tempfilePath;
}
}
return @"";
}
RCT_EXPORT_METHOD(addContact:(NSDictionary *)contactData callback:(RCTResponseSenderBlock)callback)
{
//@TODO keep addressbookRef in singleton
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
ABRecordRef newPerson = ABPersonCreate();
CFErrorRef error = NULL;
ABAddressBookAddRecord(addressBookRef, newPerson, &error);
//@TODO error handling
[self updateRecord:newPerson onAddressBook:addressBookRef withData:contactData completionCallback:callback];
}
RCT_EXPORT_METHOD(updateContact:(NSDictionary *)contactData callback:(RCTResponseSenderBlock)callback)
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
int recordID = (int)[contactData[@"recordID"] integerValue];
ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBookRef, recordID);
[self updateRecord:record onAddressBook:addressBookRef withData:contactData completionCallback:callback];
}
-(void) updateRecord:(ABRecordRef)record onAddressBook:(ABAddressBookRef)addressBookRef withData:(NSDictionary *)contactData completionCallback:(RCTResponseSenderBlock)callback
{
CFErrorRef error = NULL;
NSString *firstName = [contactData valueForKey:@"firstName"];
NSString *lastName = [contactData valueForKey:@"lastName"];
NSString *middleName = [contactData valueForKey:@"middleName"];
ABRecordSetValue(record, kABPersonFirstNameProperty, (__bridge CFStringRef) firstName, &error);
ABRecordSetValue(record, kABPersonLastNameProperty, (__bridge CFStringRef) lastName, &error);
ABRecordSetValue(record, kABPersonMiddleNameProperty, (__bridge CFStringRef) middleName, &error);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSArray* phoneNumbers = [contactData valueForKey:@"phoneNumbers"];
for (id phoneData in phoneNumbers) {
NSString *label = [phoneData valueForKey:@"label"];
NSString *number = [phoneData valueForKey:@"number"];
if ([label isEqual: @"main"]){
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef) number, kABPersonPhoneMainLabel, NULL);
}
else if ([label isEqual: @"mobile"]){
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef) number, kABPersonPhoneMobileLabel, NULL);
}
else if ([label isEqual: @"iPhone"]){
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef) number, kABPersonPhoneIPhoneLabel, NULL);
}
else{
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef) number, (__bridge CFStringRef) label, NULL);
}
}
ABRecordSetValue(record, kABPersonPhoneProperty, multiPhone, nil);
CFRelease(multiPhone);
ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSArray* emails = [contactData valueForKey:@"emailAddresses"];
for (id emailData in emails) {
NSString *label = [emailData valueForKey:@"label"];
NSString *email = [emailData valueForKey:@"email"];
ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFStringRef) email, (__bridge CFStringRef) label, NULL);
}
ABRecordSetValue(record, kABPersonEmailProperty, multiEmail, nil);
CFRelease(multiEmail);
ABAddressBookSave(addressBookRef, &error);
if (error != NULL)
{
CFStringRef errorDesc = CFErrorCopyDescription(error);
NSString *nsErrorString = (__bridge NSString *)errorDesc;
callback(@[nsErrorString]);
CFRelease(errorDesc);
}
else{
callback(@[[NSNull null]]);
}
}
RCT_EXPORT_METHOD(deleteContact:(NSDictionary *)contactData callback:(RCTResponseSenderBlock)callback)
{
CFErrorRef error = NULL;
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
int recordID = (int)[contactData[@"recordID"] integerValue];
ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBookRef, recordID);
ABAddressBookRemoveRecord(addressBookRef, record, &error);
ABAddressBookSave(addressBookRef, &error);
//@TODO handle error
callback(@[[NSNull null], [NSNull null]]);
}
@end