2014-09-06 2 views
1

전화 번호는 이렇게 표시됩니다. 전화 1 개 값 (들) 0 ABMultiValueRef 0x17674380 : $! $ (0x176740e0) - 7124779070 (0x176742a0) IOS :: ABAddressBook에서 연락 전화 번호를 얻는 방법

위의 행에서이 번호 " 7124779070"를 얻는 방법.

나는이 코드를 ios7 용으로 사용하고 있습니다. 정확하거나 잘못되었습니다. 제발 sugggest 해주세요.

int i; 
    ABAddressBookRef contactBook = ABAddressBookCreateWithOptions(NULL, NULL); 
    NSMutableArray *allData = (NSMutableArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook)); 
    CFIndex contactNum = CFArrayGetCount((__bridge CFArrayRef)(allData)); 

    for (i = 0; i < contactNum; i++) 
    { 
     ABRecordRef ref = CFArrayGetValueAtIndex((__bridge CFMutableArrayRef)(allData), i); 
     NSString* firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty); 
     NSString* lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty); 
     NSString* phonesNum = ABRecordCopyValue(ref, kABPersonPhoneProperty); 

     // Remove all formatting symbols that might be in both phone number being compared 
     NSCharacterSet *toExclude = [NSCharacterSet characterSetWithCharactersInString:@"/.()- "]; 
     phonesNum = [[phonesNum componentsSeparatedByCharactersInSet:toExclude] componentsJoinedByString: @""]; 
    NSString *phoneNumber = [[phonesNum componentsSeparatedByCharactersInSet:toExclude] componentsJoinedByString: @""]; 



     NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; 
     if (firstName!=nil) 
     { 
      [dic setObject:(__bridge id)(firstName) forKey:@"firstName"]; 

     } 
     if (lastName !=nil) { 
      [dic setObject:(__bridge id)(lastName) forKey:@"lastName"]; 

     } 
     if (phonesNum!=nil) { 
      [dic setObject:(__bridge id)(phonesNum) forKey:@"phonesNum"]; 
     } 

     [arr_Contacts addObject:dic]; 

     NSLog(@"First name %@", firstName); 
     NSLog(@"Last Name %@", lastName); 
     NSLog(@"Phone %@", phonesNum); 
    } 
+0

첫 번째 전화 번호 만 사용 하시겠습니까? – Rob

+1

[주소록 프로그래밍 가이드] (https://developer.apple.com/Library/ios/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Introduction.html)를 읽어 보셨습니까? 당신은 그렇지 않으면해야합니다. 대부분의 쟁점에 대답하지 않더라도, 당신이 묻는 것은 기본적인 코딩이 전부가 아닙니다.답변에 코드를 복사하여 붙여 넣을 수는 있지만 맹목적으로 수행하면 더 많은 문제 (혼동)가 발생합니다. – n00bProgrammer

+0

가능한 복제본 http://stackoverflow.com/a/23418263/1271826 – Rob

답변

0

전화 % @ NSLog에서 콘솔에있는 내용은 무엇입니까? 만약 전화 1 개 값 (들) 0 ABMultiValueRef 0x17674380 : $! $ (0x176740e0) - 7124779070 (0x176742a0) 직후 부분 문자열 '-'

NSString *myString = @"Phone ABMultiValueRef 0x17674380 with 1 value(s) 0: $!!$ (0x176740e0) - 7124779070 (0x176742a0)"; 
NSArray *myArray = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-"]];  

이 전화의

- (void) getContacts 
    { 
    NSMutableDictionary *response = [[NSMutableDictionary alloc] init]; 

    ABAddressBookRef contactBook = ABAddressBookCreateWithOptions(NULL, NULL); 
    arr_Contacts = [[NSMutableArray alloc] init]; 
    ABAddressBookRef allPeople = contactBook; 
    CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(allPeople); 
    CFIndex numberOfContacts = ABAddressBookGetPersonCount(allPeople); 
    NSLog(@"contact == %@",allContacts); 


    NSLog(@"numberOfContacts------------------------------------%ld",numberOfContacts); 

    for(int i = 0; i < numberOfContacts; i++){ 
     NSString* name = @""; 
     NSString* phone = @""; 
     NSString* email = @""; 

     ABRecordRef aPerson = CFArrayGetValueAtIndex(allContacts, i); 
     ABMultiValueRef fnameProperty = ABRecordCopyValue(aPerson, kABPersonFirstNameProperty); 
     ABMultiValueRef lnameProperty = ABRecordCopyValue(aPerson, kABPersonLastNameProperty); 

     ABMultiValueRef phoneProperty = ABRecordCopyValue(aPerson, kABPersonPhoneProperty);\ 
     ABMultiValueRef emailProperty = ABRecordCopyValue(aPerson, kABPersonEmailProperty); 

     NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty); 
     NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty); 


     if (fnameProperty != nil) { 
      name = [NSString stringWithFormat:@"%@", fnameProperty]; 
     } 
     if (lnameProperty != nil) { 
      name = [name stringByAppendingString:[NSString stringWithFormat:@" %@", lnameProperty]]; 
     } 

     if ([phoneArray count] > 0) { 
      if ([phoneArray count] > 1) { 
       for (int i = 0; i < [phoneArray count]; i++) { 
        phone = [phone stringByAppendingString:[NSString stringWithFormat:@"%@, ", [phoneArray objectAtIndex:i]]]; 
       } 
      }else { 
       phone = [NSString stringWithFormat:@"%@", [phoneArray objectAtIndex:0]]; 
      } 
     } 

     if ([emailArray count] > 0) { 
      if ([emailArray count] > 1) { 
       for (int i = 0; i < [emailArray count]; i++) { 
        email = [email stringByAppendingString:[NSString stringWithFormat:@"%@\n", [emailArray objectAtIndex:i]]]; 
       } 
      }else { 
       email = [NSString stringWithFormat:@"%@", [emailArray objectAtIndex:0]]; 
      } 
     } 
     NSLog(@"NAME : %@",name); 
     NSLog(@"PHONE: %@",phone); 
     NSLog(@"EMAIL: %@",email); 
     NSLog(@"\n"); 
     [response setObject:name forKey:@"name"]; 
     [response setObject:phone forKey:@"phone"]; 
     [response setObject:email forKey:@"email"]; 

     [arr_Contacts addObject:response]; 
    } 

    } 
를 얻을 내 방법입니다

건배

+0

이 코드는 ios 7에서 실행합니다. – Ravikumar

+0

예 iOS 7에서 사용합니다. – Salsores

+0

재생 해 주셔서 감사합니다 .... – Ravikumar

1

첫째, 권한을 요청 :

ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus(); 

if (status != kABAuthorizationStatusAuthorized && status != kABAuthorizationStatusNotDetermined) { 
    // tell user to enable contacts in privacy settings 
    NSLog(@"You previously denied access: You must enable access to contacts in settings"); 

    return; 
} 

CFErrorRef error = NULL; 
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); 
if (!addressBook) { 
    NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error)); 
    return; 
} 

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { 
    if (error) { 
     NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error)); 
    } 

    if (granted) { 
     [self getContacts:addressBook]; 
    } else { 
     // tell user to enable contacts in privacy settings 
     NSLog(@"You just denied access: You must enable access to contacts in settings"); 
    } 

    CFRelease(addressBook); 
}); 

둘째, 전화 번호를 검색하기 위해 사용 ABMultiValueCopyValueAtIndex : 추가 문제의

- (void)getContacts:(ABAddressBookRef)addressBook 
{ 
    NSArray *allData = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook)); 
    NSInteger contactCount = [allData count]; 

    for (int i = 0; i < contactCount; i++) { 
     ABRecordRef person = CFArrayGetValueAtIndex((__bridge CFArrayRef)allData, i); 

     NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty)); 
     NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty)); 

     NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; 
     if (firstName) { 
      dictionary[@"firstName"] = firstName; 
     } 
     if (lastName) { 
      dictionary[@"lastName"] = lastName; 
     } 

     ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty); 
     CFIndex phoneNumberCount = ABMultiValueGetCount(phones); 

     if (phoneNumberCount > 0) { 
      NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, 0)); 
      dictionary[@"phone"] = phone; 
     } 

     // or if you wanted to iterate through all of them, you could do something like: 
     // 
     // for (int j = 0; j < phoneNumberCount; j++) { 
     //  NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, j)); 
     // 
     //  // do something with `phone` 
     // } 

     if (phones) { 
      CFRelease(phones); 
     } 

     [arr_Contacts addObject:dictionary]; 
    } 
} 

몇 위 주소 다음 ABAddressBookCreateWithOptions

  1. 을 변경 가능한 배열을 반환하지 않습니다. 그것은 불변의 배열입니다. 모든 변경 가능한 참조를 변경 불가능한 것으로 바꾸십시오.

  2. 당신은 당신이 어떤 물체가 Create 또는 이름에 Copy 중 하나와 코어 재단 메서드에서 반환 해제에 대한 책임, 즉 것으로는 Create Rule을 존중해야합니다. 개체가 수신자 부담 브리지 (예 : 연락처 배열, 이름 문자열, 성 문자열 등)를 지원하는 경우 CFBridgingRelease 또는 __bridge_transfer을 사용하여 소유권을 ARC로 이전 할 수 있습니다. 개체가 무료 전화 브리지 (예 : 위의 phones 또는 addressBook 개체)를 지원하지 않는 경우 문제의 개체에 대해 CFRelease을 명시 적으로 호출해야합니다.

    은 정적 분석을 통해 코드를 실행해야합니다 ( + 명령 + B, 변화 또는 선택 엑스 코드의 "제품"메뉴에서 "분석"), 그리고 당신을 위해 문제의 이러한 종류를 식별합니다 .

  3. ABAddressBookCreateWithOptions과 같은 함수가 오류 매개 변수를 제공하면이 매개 변수를 사용해야합니다. 위의 CFErrorRef 개체의 올바른 사용법을 설명합니다.