ARCHIVES

태그

신고하기

상단 메뉴 페이지

기본 콘텐츠로 건너뛰기

[iOS] 간단하게 사용자 전화번호 획득하기

아이폰에서 사용자 전화번호를 가져오는 방법이다.

ConteactsUI 를 사용해서 바로 가져올 수 있다.


//

//  ViewController.swift

//  ContactsTest

//

//  Created by jae hwan choo on 2022/05/24.

//


import UIKit

import Contacts

import ContactsUI


class ViewController: UIViewController {


    @IBOutlet weak var labelName: UILabel!

    @IBOutlet weak var labelPhone: UILabel!


    override func viewDidLoad() {

        super.viewDidLoad()

    }


    @IBAction func actionGet(_ sender: Any) {

        

        // 아래의 권한을 추가한다.

        // Privacy - Contacts Usage Description

        

        showContactsPicker(self)

    }

    

    /*-----------------------------------------------------------------------

    * 주소록 선택화면 보여준다. CNContactPickerDelegate에서 처리

    *-----------------------------------------------------------------------*/

    var contacts: NSMutableArray = NSMutableArray()

    

    func showContactsPicker(_ vc: UIViewController?) {

        let contactStore = CNContactStore()

        contactStore.requestAccess(for: .contacts) { (granted, error) in

            if granted {

                let contactPicker       = CNContactPickerViewController()

                contactPicker.delegate  = self // CNContactPickerDelegate

                contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey,

                                                       CNContactEmailAddressesKey,

                                                       CNContactJobTitleKey,

                                                       CNContactPostalAddressesKey]

                

                if let nav = vc?.navigationController { // present 사용

                    nav.present(contactPicker, animated: true, completion: nil)

                } else {

                    vc?.present(contactPicker, animated: true, completion: nil)

                }

                

            } else {

                print("에러: \(String(describing: error))")

            }

        }

    }

}


//

// MARK: CNContactPickerDelegate

//

extension ViewController: CNContactPickerDelegate {

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

        print(contact.givenName)

        print(contact.familyName)

        print(contact.organizationName)

        

        labelName.text = "이름: \(contact.givenName) \(contact.familyName)"


        if contact.phoneNumbers.count == 0 {

            print("전화번호 정보가 없다.")

            return

        }

        

        // contact properties 는 phone numbers, email,

        // CNLabeledValue 를 가진 array 와 같은 multiple values 를 가진다.

        labelPhone.text = "전번: \(contact.phoneNumbers[0].value.stringValue)"

    }

}

댓글