Swift-アドレス帳情報の読み出し


1、アドレス帳アクセス紹介アドレス帳はデータベースで、アドレス帳、電話帳とも呼ばれ、連絡先に関する情報が格納されています.アクセス通信録を実現するには,(1)AddressBook.frameworkフレームワーク:インタフェースがなく、コードによってすべての連絡先情報(2)AddressBookUIを取得する.frameworkフレームワーク:システムが提供する通信録インタラクティブインタフェースからアクセス
2.連絡先レコードの属性1つの連絡先レコードには、多くの属性があり、これらの属性は単値属性と多値属性に分けられる.(1)単一属性は、1つの値のみの属性:kABPersonLastNameProperty:姓kABPersonFirstNameProperty:名kABPersonMiddleNameProperty:中間名kABPersonPrefixProperty:プレフィックスkABPersonSuffixProperty:接尾辞kABPersonLastNamePhoneticProperty:姓漢語ピンインまたは音標kPerABsonFirstNamePhoneticProperty:名前中国語ピンインまたは音標kABPersonNicknameProperty:ニックネームkABPersonOrganizationProperty:会社(組織)kABPersonJobTitleProperty:職位kABPersonDepartmentProperty:部門kABPersonNoteProperty:注釈
(2)多値属性は複数の値を含む集合タイプ:kABPersonPhoneProperty:電話kABPersonEmailProperty:E mail kABPersonAddressProperty:アドレスkABPersonURLProperty:URL属性kABPersonDateProperty:記念日kABPersonInstantMesageProperty:インスタント通信(IM)の取得kABPersonSocialProfileProperty:SNSアカウントkABPersonRelatedNamesProperty:親族関係者
3、多値属性ラベルのローカル名は、多値属性にlabel(ラベル)、value(値)、IDなどの部分を含み、ラベルと値は重複可能であり、IDは重複できない.ラベルについては、ABAddressBookCopyLocalizedLabel()メソッドを使用してローカルラベル名(ワーク、ホームなど)に変更できます.さもないとプリントアウトされます!! , !! このようなデータ.
4、次の例では、コードを使用してすべての連絡先を巡り、関連属性を印刷出力します.
import UIKit
import AddressBook
import AddressBookUI

class ViewController: UIViewController {

    //address Book  ,         
    var addressBook:ABAddressBookRef?

    override func viewDidLoad() {
        super.viewDidLoad()

        //          ,      

        var error:Unmanaged<CFErrorRef>?
        addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

        //      
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        if (sysAddressBookStatus == ABAuthorizationStatus.NotDetermined) {
            print("requesting access...")
// var errorRef:Unmanaged<CFError>? = nil
            //addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
            ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
                if success {
                    //            
                    self.readRecords();
                }
                else {
                    print("error")
                }
            })
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Denied || sysAddressBookStatus == ABAuthorizationStatus.Restricted) {
            print("access denied")
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Authorized) {
            print("access granted")
            //            
            self.readRecords();
        }
    }

    //            
    func readRecords(){
        let sysContacts:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
        for contact in sysContacts {
            //   
            let lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""
            print(" :\(lastName)")

            //   
            let firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""
            print(" :\(firstName)")

            //  
            let nikeName = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as! String? ?? ""
            print("  :\(nikeName)")

            //  (  )
            let organization = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as! String? ?? ""
            print("  (  ):\(organization)")

            //  
            let jobTitle = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as! String? ?? ""
            print("  :\(jobTitle)")

            //  
            let department = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as! String? ?? ""
            print("  :\(department)")

            //  
            let note = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as! String? ?? ""
            print("  :\(note)")

            //    
            let phoneValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonPhoneProperty).takeRetainedValue()
            if phoneValues != nil {
                print("  :\(ABMultiValueGetCount(phoneValues))")
                if ABMultiValueGetCount(phoneValues)==1 {
                    for i in 0 ..< ABMultiValueGetCount(phoneValues){
                        if ABMultiValueCopyLabelAtIndex(phoneValues, i) != nil {

                            //      
                            let phoneLabel = ABMultiValueCopyLabelAtIndex(phoneValues, i).takeRetainedValue()
                                as CFStringRef;
                            //        (        ,  work、home)
                            let localizedPhoneLabel = ABAddressBookCopyLocalizedLabel(phoneLabel).takeRetainedValue() as String

                            let value = ABMultiValueCopyValueAtIndex(phoneValues, i)
                            let phone = value.takeRetainedValue() as! String
                            print(" \(localizedPhoneLabel):\(phone)")
                        }
                    }
                }
            }

            //  Email
            let emailValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonEmailProperty).takeRetainedValue()
            if emailValues != nil {
                print("Email:")
                for i in 0 ..< ABMultiValueGetCount(emailValues){
                    if ABMultiValueCopyLabelAtIndex(emailValues, i) != nil {
                        //      
                        let label = ABMultiValueCopyLabelAtIndex(emailValues, i).takeRetainedValue()
                            as CFStringRef;
                        let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String

                        let value = ABMultiValueCopyValueAtIndex(emailValues, i)
                        let email = value.takeRetainedValue() as! String
                        print(" \(localizedLabel):\(email)")
                    }
                }
            }

            //    
            let addressValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonAddressProperty).takeRetainedValue()
            if addressValues != nil {
                print("  :")
                for i in 0 ..< ABMultiValueGetCount(addressValues){

                    //      
                    let label = ABMultiValueCopyLabelAtIndex(addressValues, i).takeRetainedValue()
                        as CFStringRef;
                    let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String

                    let value = ABMultiValueCopyValueAtIndex(addressValues, i)
                    let addrNSDict:NSMutableDictionary = value.takeRetainedValue()
                        as! NSMutableDictionary
                    let country:String = addrNSDict.valueForKey(kABPersonAddressCountryKey as String)
                        as? String ?? ""
                    let state:String = addrNSDict.valueForKey(kABPersonAddressStateKey as String)
                        as? String ?? ""
                    let city:String = addrNSDict.valueForKey(kABPersonAddressCityKey as String)
                        as? String ?? ""
                    let street:String = addrNSDict.valueForKey(kABPersonAddressStreetKey as String)
                        as? String ?? ""
                    let contryCode:String = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey as String) as? String ?? ""
                    print(" \(localizedLabel): Contry:\(country) State:\(state) ")
                    print("City:\(city) Street:\(street) ContryCode:\(contryCode) ")
                }
            }

            //     
            let dateValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonDateProperty).takeRetainedValue()
            if dateValues != nil {
                print("   :")
                for i in 0 ..< ABMultiValueGetCount(dateValues){

                    //      
                    let label = ABMultiValueCopyLabelAtIndex(emailValues, i).takeRetainedValue()
                        as CFStringRef;
                    let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String
                    let value = ABMultiValueCopyValueAtIndex(dateValues, i)
                    let date = (value.takeRetainedValue() as? NSDate)?.description ?? ""
                    print(" \(localizedLabel):\(date)")
                }
            }

            //      (IM)
            let imValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonInstantMessageProperty).takeRetainedValue()
            if imValues != nil {
                print("    (IM):")
                for i in 0 ..< ABMultiValueGetCount(imValues){
                    if ABMultiValueCopyLabelAtIndex(imValues, i) != nil {
                        //      
                        let label = ABMultiValueCopyLabelAtIndex(imValues, i).takeRetainedValue()
                            as CFStringRef;
                        let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String
                        let value = ABMultiValueCopyValueAtIndex(imValues, i)
                        let imNSDict:NSMutableDictionary = value.takeRetainedValue()
                            as! NSMutableDictionary
                        let serves:String = imNSDict.valueForKey(kABPersonInstantMessageServiceKey as String) as? String ?? ""
                        let userName:String = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey as String) as? String ?? ""
                        print(" \(localizedLabel): Serves:\(serves) UserName:\(userName)")
                    }
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}