关于ios:在Swift中以编程方式创建联系人

Create a contact programmatically in Swift

我正在创建一个需要在该设备的通讯录中添加联系人的应用程序。
当我仅使用名字和姓氏将联系人添加到设备时,一切正常。但是,当我尝试添加电话号码时,该应用也会崩溃。
有人能看到我在做什么错吗?

预先感谢!

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
    let firstName ="Firstname"
    let lastName ="Lastname"
    let telephoneNumber ="1234567890"
    let notes ="This is a note"

    let person: ABRecordRef = ABPersonCreate().takeRetainedValue()

    let couldSetFirstName = ABRecordSetValue(person, kABPersonFirstNameProperty, firstName as CFTypeRef, nil)

    let couldSetLastName = ABRecordSetValue(person, kABPersonLastNameProperty, lastName as CFTypeRef, nil)
    let couldSetPhoneNumber = ABRecordSetValue(person, kABPersonPhoneProperty, telephoneNumber as CFTypeRef, nil)

    let couldSetNotes = ABRecordSetValue(person, kABPersonNoteProperty, notes, nil)

    var error: Unmanaged<CFErrorRef>? = nil

    let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error)

    if couldAddPerson {
        println("Added person")
    } else{
        println("Failed to add person")
        return nil
    }

    if ABAddressBookHasUnsavedChanges(inAddressBook){

        var error: Unmanaged<CFErrorRef>? = nil
        let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error)

        if couldSaveAddressBook{
            println("Saved address book")
        } else {
            println("Failed to save address book")
        }

        if couldSetFirstName && couldSetLastName {
            println("Succesfully set first and last name")
        } else{
            println("Failed to set first and last name")
        }
    }

    return person

您正在传递一个字符串来设置kABPersonPhoneProperty的值,这是不正确的。电话号码不是字符串属性;这是一个多值属性。您需要使用以下代码中的代码进行设置:如何在iPhone SDK中的通讯录中创建联系人? (这是Objective-C,但应该易于翻译。)

1
2
3
4
5
6
7
NSString *phone = @"0123456789"; // the phone number to add

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

ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, &anError); // set the phone number property