在Swift中以编程方式创建联系人

时间:2015-01-15 15:21:27

标签: ios swift addressbook abaddressbook

我正在创建一个应用程序,需要将联系人添加到该设备的地址簿中。 当我仅使用名字和姓氏将联系人添加到设备时,一切都很顺利。但是,当我尝试添加电话号码时,应用程序崩溃了。 谁能看到我在这里做错了什么?

提前致谢!

    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

1 个答案:

答案 0 :(得分:2)

您正在传递一个字符串来设置kABPersonPhoneProperty的值,这是不正确的。电话号码不是字符串属性;这是一个多价值的财产。你需要使用像这里的代码那样设置它:How to create contacts in address book in iPhone SDK?(这是Objective-C,但应该直接翻译。)

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