ma11hew28
ma11hew28

Reputation: 126487

iOS Address Book: Can a person record have a nil first name?

If a contact's first name or last name is blank, will the value be nil or ""?

Upvotes: 0

Views: 1337

Answers (2)

Hristo Atanasov
Hristo Atanasov

Reputation: 1266

If a person don't have first or last name the value will be nil. If you want to cast it to an empty string you can do this:

            // Getting the first and the last name of person
        let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)?;
        let firstName: NSObject? = Unmanaged<NSObject>.fromOpaque(firstNameTemp!.toOpaque()).takeRetainedValue();
        var first_name = "";
        if firstName != nil {
            first_name = firstName! as NSString;
        }

        let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)?;
        let lastName: NSObject? = Unmanaged<NSObject>.fromOpaque(lastNameTemp!.toOpaque()).takeRetainedValue();
        var last_name = "";
        if lastName != nil {
            last_name = lastName! as NSString;
        }

Upvotes: 2

ma11hew28
ma11hew28

Reputation: 126487

The value will be nil as of Xcode 6 Beta 4.

To see for yourself, run the following code twice:

// AppDelegate.swift

import AddressBookUI
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow!

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        var error: Unmanaged<CFError>?
        let addressBookTemp = ABAddressBookCreateWithOptions(nil, &error)
        if !addressBookTemp {
            println(error)
            return true
        }

        let addressBook = Unmanaged<NSObject>.fromOpaque(addressBookTemp.toOpaque()).takeRetainedValue()
        ABAddressBookRequestAccessWithCompletion(addressBook, nil)

        var allPeople: NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
        println("allPeople.count: \(allPeople.count)")

        for person in allPeople {
            let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)
            let firstName: NSObject! = Unmanaged<NSObject>.fromOpaque(firstNameTemp.toOpaque()).takeRetainedValue()

            if firstName {
                println("firstName: \(firstName)")
            } else {
                println("fristName is nil")
            }

            let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)
            let lastName: NSObject! = Unmanaged<NSObject>.fromOpaque(lastNameTemp.toOpaque()).takeRetainedValue()

            if lastName {
                println("lastName: \(lastName)")
            } else {
                println("lastName is nil")
            }
        }
        return true
    }
}

Upvotes: 2

Related Questions