iOS/SwiftUI

SwiftUI) 연락처 정보 가져오기

Brad_Heo 2023. 11. 20. 13:40

전체 코드

import SwiftUI
import Contacts

struct ContentView: View {
    @State private var contact: [CNContact] = []

    var body: some View {
        VStack {
            List {
                ForEach(contact, id: \.self) { info in
                    Text(info.givenName)
                }
            }
        }
        .padding()
        .onAppear {
            readAddress()
        }
    }

    func readAddress() {
        let store = CNContactStore()
        let request: CNContactFetchRequest = getCNContactFetchRequest()

        request.sortOrder = .userDefault

        DispatchQueue.global(qos: .background).async {
            store.requestAccess(for: .contacts) { (granted, error) in
                guard granted else {
                    print("no")
                    return
                }

                do {
                    try store.enumerateContacts(with: request) { (contact, stop) in
                        guard let phoneNumber = contact.phoneNumbers.first?.value.stringValue else { return }

                        self.contact.append(contact)
                    }
                } catch let error {
                    print(error.localizedDescription)
                }
            }
        }
    }

    func getCNContactFetchRequest() -> CNContactFetchRequest {
        let keys = [
            CNContactGivenNameKey,
            CNContactPhoneNumbersKey
        ] as [CNKeyDescriptor]

        return CNContactFetchRequest(keysToFetch: keys)
    }
}

#Preview {
    ContentView()
}

info.plist에서 권한 설정 후 CNContactStore() 객체를 먼저 선언합니다.

스크린샷 2023-11-20 오후 12 11 16 스크린샷 2023-11-20 오후 12 12 03

그 다음 연락처에서 어떠한 정보를 가져오는지 설정을 해야 합니다.

저 같은 경우 getCNContactFetchRequest함수를 보시면 이름, 핸드폰 번호를 가져오도록 설정했습니다.

만약 설정한 정보가 아닌 데이터를 호출할 시 Thread 4: "A property was not requested when contact was fetched." 오류 메세지가 나오면서 앱이 강제 종료 됩니다.

그 다음 권한을 확인하고, 로직으로 들어갑니다.

기존에 설정해둔 정보로 연락처 정보를 가져오는 거죠. 클로저는 연락처 한개당 한번 실행됩니다. 즉 10개가 있다면 10번 도는것이죠.

해당 데이터를 빈배열에 넣고 List로 표현해주면 아래와 같은 화면이 나오게 됩니다.

스크린샷 2023-11-20 오후 1 36 12