전체 코드
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() 객체를 먼저 선언합니다.
그 다음 연락처에서 어떠한 정보를 가져오는지 설정을 해야 합니다.
저 같은 경우 getCNContactFetchRequest
함수를 보시면 이름, 핸드폰 번호를 가져오도록 설정했습니다.
만약 설정한 정보가 아닌 데이터를 호출할 시 Thread 4: "A property was not requested when contact was fetched."
오류 메세지가 나오면서 앱이 강제 종료 됩니다.
그 다음 권한을 확인하고, 로직으로 들어갑니다.
기존에 설정해둔 정보로 연락처 정보를 가져오는 거죠. 클로저는 연락처 한개당 한번 실행됩니다. 즉 10개가 있다면 10번 도는것이죠.
해당 데이터를 빈배열에 넣고 List로 표현해주면 아래와 같은 화면이 나오게 됩니다.
'iOS > SwiftUI' 카테고리의 다른 글
SwiftUI) `.fileImporter` 사용시 Error message. (0) | 2024.02.14 |
---|---|
SwiftUI `.fullScreenCover` `enum` 활용해 화면 전환 (0) | 2023.11.13 |
SwiftUI TextField (0) | 2023.11.10 |
SwiftUI ZStack 활용 (0) | 2023.11.07 |
SwiftUI) NavigationBar 뒤로가기 버튼 안보이게 하기 (0) | 2023.06.12 |