2013-03-25 36 views
32

Xin chào! Có cách nào khi người dùng chạm vào nút mà người dùng có thể thêm hoặc cập nhật liên hệ vào Sổ địa chỉ liên hệ của Apple thực tế không? Một số lễ hội có câu trả lời qua email bao gồm "thẻ tên" mà người nhận có thể tải xuống và tìm thấy trong sổ liên lạc của họ.iOS - thêm liên hệ vào Danh bạ?

Trả lời

68

Nếu làm điều này trong iOS 9 hoặc mới hơn, bạn nên sử dụng Contacts khuôn khổ:

@import Contacts; 

Bạn cũng cần phải cập nhật Info.plist của bạn, thêm một NSContactsUsageDescription để giải thích lý do tại sao ứng dụng của bạn yêu cầu quyền truy cập vào danh bạ.

Sau đó, khi sau đó bạn muốn lập trình thêm số liên lạc, sau đó bạn có thể làm một cái gì đó như:

CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; 
if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) { 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Access to contacts." message:@"This app requires access to contacts because ..." preferredStyle:UIAlertControllerStyleActionSheet]; 
    [alert addAction:[UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil]; 
    }]]; 
    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]]; 
    [self presentViewController:alert animated:TRUE completion:nil]; 
    return; 
} 

CNContactStore *store = [[CNContactStore alloc] init]; 

[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { 
    if (!granted) { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // user didn't grant access; 
      // so, again, tell user here why app needs permissions in order to do it's job; 
      // this is dispatched to the main queue because this request could be running on background thread 
     }); 
     return; 
    } 

    // create contact 

    CNMutableContact *contact = [[CNMutableContact alloc] init]; 
    contact.familyName = @"Doe"; 
    contact.givenName = @"John"; 

    CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"312-555-1212"]]; 
    contact.phoneNumbers = @[homePhone]; 

    CNSaveRequest *request = [[CNSaveRequest alloc] init]; 
    [request addContact:contact toContainerWithIdentifier:nil]; 

    // save it 

    NSError *saveError; 
    if (![store executeSaveRequest:request error:&saveError]) { 
     NSLog(@"error = %@", saveError); 
    } 
}]; 

Hoặc, thậm chí tốt hơn, nếu bạn muốn thêm số liên lạc bằng cách sử dụng khuôn khổ ContactUI (cho người sử dụng xác nhận trực quan của liên lạc và cho họ chỉnh nó như là họ thấy phù hợp), bạn có thể nhập tất cả các khuôn khổ:

@import Contacts; 
@import ContactsUI; 

và sau đó:

CNContactStore *store = [[CNContactStore alloc] init]; 

// create contact 

CNMutableContact *contact = [[CNMutableContact alloc] init]; 
contact.familyName = @"Smith"; 
contact.givenName = @"Jane"; 

CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"301-555-1212"]]; 
contact.phoneNumbers = @[homePhone]; 

CNContactViewController *controller = [CNContactViewController viewControllerForUnknownContact:contact]; 
controller.contactStore = store; 
controller.delegate = self; 

[self.navigationController pushViewController:controller animated:TRUE]; 

Câu trả lời gốc của tôi, sử dụng các khung AddressBookAddressBookUI dành cho iOS trước 9, bên dưới. Nhưng nếu chỉ hỗ trợ iOS 9 trở lên, hãy sử dụng các khung công tác ContactsContactsUI như được nêu ở trên.

-

Nếu bạn muốn thêm một số liên lạc vào sổ địa chỉ của người sử dụng, bạn sử dụng AddressBook.Framework để tạo ra một số liên lạc, và sau đó bạn sử dụng AddressBookUI.Framework để trình bày các giao diện người dùng cho phép người dùng để thêm vào sổ địa chỉ cá nhân của họ bằng cách sử dụng ABUnknownPersonViewController. Vì vậy, bạn có thể:

  1. Thêm AddressBook.FrameworkAddressBookUI.Framework vào danh sách của bạn dưới Link Binary With Libraries;

  2. Import các file .h:

    #import <AddressBook/AddressBook.h> 
    #import <AddressBookUI/AddressBookUI.h> 
    
  3. Viết mã để tạo ra một số liên lạc, ví dụ:

    // create person record 
    
    ABRecordRef person = ABPersonCreate(); 
    
    // set name and other string values 
    
    ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef) venueName, NULL); 
    
    if (venueUrl) { 
        ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); 
        ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) venueUrl, kABPersonHomePageLabel, NULL); 
        ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil); 
        CFRelease(urlMultiValue); 
    } 
    
    if (venueEmail) { 
        ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); 
        ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) venueEmail, kABWorkLabel, NULL); 
        ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil); 
        CFRelease(emailMultiValue); 
    } 
    
    if (venuePhone) { 
        ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); 
        NSArray *venuePhoneNumbers = [venuePhone componentsSeparatedByString:@" or "]; 
        for (NSString *venuePhoneNumberString in venuePhoneNumbers) 
         ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) venuePhoneNumberString, kABPersonPhoneMainLabel, NULL); 
        ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil); 
        CFRelease(phoneNumberMultiValue); 
    } 
    
    // add address 
    
    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); 
    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init]; 
    
    if (venueAddress1) { 
        if (venueAddress2) 
         addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:@"%@\n%@", venueAddress1, venueAddress2]; 
        else 
         addressDictionary[(NSString *) kABPersonAddressStreetKey] = venueAddress1; 
    } 
    if (venueCity) 
        addressDictionary[(NSString *)kABPersonAddressCityKey] = venueCity; 
    if (venueState) 
        addressDictionary[(NSString *)kABPersonAddressStateKey] = venueState; 
    if (venueZip) 
        addressDictionary[(NSString *)kABPersonAddressZIPKey] = venueZip; 
    if (venueCountry) 
        addressDictionary[(NSString *)kABPersonAddressCountryKey] = venueCountry; 
    
    ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL); 
    ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL); 
    CFRelease(multiAddress); 
    
    // let's show view controller 
    
    ABUnknownPersonViewController *controller = [[ABUnknownPersonViewController alloc] init]; 
    
    controller.displayedPerson = person; 
    controller.allowsAddingToAddressBook = YES; 
    
    // current view must have a navigation controller 
    
    [self.navigationController pushViewController:controller animated:YES]; 
    
    CFRelease(person); 
    

Xem ABUnknownPersonViewController Class Reference hoặc phần Prompting the User to Create a New Person Record from Existing Data của Địa chỉ Hướng dẫn lập trình sách.

+0

lý do bạn đặt "status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied"? – fechidal89

+0

typo. nên bị từ chối || bị hạn chế. xem câu trả lời đã sửa đổi. – Rob

+0

Bạn có thể vui lòng giúp tôi tìm hiểu lý do tại sao tôi không thể sử dụng số nhận dạng tùy chỉnh khi tạo giá trị được gắn nhãn như sau: 'let app = CNLabeledValue (label:" App ", value: appURL); contact.urlAddresses.append (app) 'Xin lưu ý rằng tôi có thể sử dụng nó nếu iPhone chỉ sử dụng iCloud để lưu danh bạ. Nhưng nếu tôi đang sử dụng danh bạ Google thì nó không hoạt động. –

0
@import Contacts; 
-(void)addToContactList 
{ 
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; 

if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) { 

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can add the desired contact" preferredStyle:UIAlertControllerStyleAlert]; 

    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; 

    [self presentViewController:alert animated:TRUE completion:nil]; 

    return; 

} 

CNContactStore *store = [[CNContactStore alloc] init]; 

[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { 

    if (!granted) { 

     dispatch_async(dispatch_get_main_queue(), ^{ 

      // user didn't grant access; 

      // so, again, tell user here why app needs permissions in order to do it's job; 

      // this is dispatched to the main queue because this request could be running on background thread 

     }); 

     return; 

    } 



    // create contact 



    CNMutableContact *contact = [[CNMutableContact alloc] init]; 

    contact.givenName = @"Test"; 

    contact.familyName = @"User"; 

    CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"91012-555-1212"]]; 

    contact.phoneNumbers = @[homePhone]; 



    CNSaveRequest *request = [[CNSaveRequest alloc] init]; 

    [request addContact:contact toContainerWithIdentifier:nil]; 



    // save it 



    NSError *saveError; 

    if (![store executeSaveRequest:request error:&saveError]) { 

     NSLog(@"error = %@", saveError); 

    } 

}]; 

} 
2

Để trình bày điều khiển tiếp xúc mặc định

Bước 1: Thêm ContactUi.Khung thành dự án và nhập khẩu

#import <Contacts/Contacts.h> 
    #import <ContactsUI/ContactsUI.h> 

Bước 2: Thêm mã này

-(void)showAddContactController{ 
     //Pass nil to show default contact adding screen 
     CNContactViewController *addContactVC = [CNContactViewController viewControllerForNewContact:nil]; 
     addContactVC.delegate=self; 
     UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addContactVC]; 
     [viewController presentViewController:navController animated:NO completion:nil]; 
    } 

Bước 3:

Để nhận được cuộc gọi trở lại khi nhấn XONG hoặc CANCEL, Thêm <CNContactViewControllerDelegate> và thực hiện phương thức ủy nhiệm.

- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact{ 
    //You will get the callback here 
} 
Các vấn đề liên quan