티스토리 뷰
[iOS] Contacts Framework 의 사용법 (CNContact, CNContactStore, Save/Fetch Contacts)
beankhan 2017. 8. 15. 17:10출처
개요
Contact Object
CNContact 을 상속받은 CNMutableContact 은 mutable 한 속성을 가지고 있으며
contact properties 를 수정할 수 있다.
contact properties 는 phone numbers, email,
CNLabeledValue 를 가진 array 와 같은 multiple values 를 가진다.
Label 는 thread-safe, immutable tuple 속성을 가지며
home, work 와 같이 각각의 value 를 가리킨다.
Create Contact Example
fileprivate func saveContact() -> Bool {
let contact = CNMutableContact()
contact.givenName = "John"
contact.familyName = "Appleseed"
let homeEmail = CNLabeledValue(label:CNLabelHome,
value:"john@example.com" as NSString)
let workEmail = CNLabeledValue(label:CNLabelWork,
value:"j.appleseed@icloud.com" as NSString)
contact.emailAddresses = [homeEmail, workEmail]
let phoneNumberInfo = CNLabeledValue(label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:"(408) 555-0126"))
contact.phoneNumbers = [ phoneNumberInfo ]
let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
var birthday = DateComponents()
birthday.day = 1
birthday.month = 4
birthday.year = 1988
contact.birthday = birthday
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
var result = false
do {
try store.execute(saveRequest)
result = true
} catch let error {
print("error occured : \(error.localizedDescription)")
}
return result
}
Formatting and Localization
Name and postal address Formating Example
let contact = CNMutableContact()
contact.givenName = "John"
contact.familyName = "Appleseed"
let fullName = CNContactFormatter.string(from: contact, style: .fullName)
print(fullName ?? "")
// John Appleseed
let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
let postalString = CNPostalAddressFormatter.string(from: homeAddress,
style: .mailingAddress)
print(postalString)
// 1 Infinite Loop
// Cupertino
// CA
// 95014
CNContact 의 localizedString(forKey:) 와
CNLabeledValue.localizedString(forLabel:) 등을 이용하여
device 의 current locale setting 에 따른 localizing 을 지원할 수 있다.
Localizing a given name Example
// device locale is Spanish
let displayName = CNContact.localizedString(forKey: CNContactNicknameKey)
print(displayName)
// alias
let displayLabel = CNLabeledValue<NSString>.localizedString(forLabel: CNLabelHome)
print(displayLabel)
// casa
Fetching Contact
필요하면 immutable 한 fetch result 를 안전하게 main thread 로
callBack 을 줄 수 있다.
Contact framework 는 contact 을 fetch 하기위해
predefined 된 predicates 와 keysToFetch property 와 같은
몇 가지 방법을 제공한다.
contact 을 filtering 하기 위한 몇가지 predicate 중
하나는 이름을 통한 검색이 있다.
predicateForContacts(matchingName:) 을 이용하면 된다.
포괄적이거나 compound predicates 는 제공되지 않는다.
keysToFetch 는 가져오는 contact properties 를 지정할 수 있다.
Fetch Example
let store = CNContactStore()
var results: [CNContact]?
do {
let fetchPropertes = [CNContactGivenNameKey, CNContactFamilyNameKey]
let predicate = CNContact.predicateForContacts(matchingName: "Appleseed")
results = try store.unifiedContacts(matching: predicate,
keysToFetch: fetchPropertes as [CNKeyDescriptor])
} catch let error {
print("error occured! : \(error.localizedDescription)")
}
print(results ?? "")
Fetch Example Using Key Descriptor
let keysToFetch = [CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
Privacy
let store = CNContactStore()
store.requestAccess(for: .contacts) { (result, error) in
}
Partial Contacts
if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) {
print("\(contact.phoneNumbers)")
} else {
//Refetch the keys
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
let refetchedContact: CNContact?
do {
refetchedContact = try store.unifiedContact(withIdentifier: contact.identifier,
keysToFetch: keysToFetch as [CNKeyDescriptor])
} catch let error {
print("error occured! :\(error.localizedDescription)")
}
}
Unified Contacts
Saving Contacts
Save New Contact Example
// Creating a new contact
let newContact = CNMutableContact()
newContact.givenName = "John"
newContact.familyName = "Appleseed"
// Saving contact
let saveRequest = CNSaveRequest()
saveRequest.add(newContact, toContainerWithIdentifier: nil)
do {
try store.execute(saveRequest)
} catch let error {
print("\(error.localizedDescription)")
}
Saving a Modified Contact
let mutableContact = contact.mutableCopy() as! CNMutableContact
let newEmail = CNLabeledValue(label: CNLabelHome, value: "john@example.com" as NSString)
mutableContact.emailAddresses.append(newEmail)
let saveRequest = CNSaveRequest()
saveRequest.update(mutableContact)
do {
try store.execute(saveRequest)
} catch let error {
print("\(error.localizedDescription)")
}
Contact Changed Notifications
Containers and Groups
'iOS 개발 > iOS' 카테고리의 다른 글
PHImageManager requestImage 의 TargetSize 별 속도차이 (0) | 2021.01.22 |
---|---|
[iOS] KeyChain 에 저장된 값은 앱 삭제 전까지 정말 사라지지 않는가 (0) | 2017.09.28 |
[iOS] CALayer 의 개념 (CATextLayer, CAShapeLayer, CAGradientLayer) (0) | 2017.07.16 |
[iOS] KeyChain 의 Key (SecKeyRef) 를 NSData 형식으로 변경하기 (0) | 2017.06.22 |
[iOS] iCloud Backup 이 되지 않도록 막는 방법 (0) | 2017.06.21 |
- Total
- Today
- Yesterday
- HTTP
- AWS
- dictionary
- coredata
- thread
- Arc
- Block
- NSManagedObjectModel
- workerThread
- 읽기 좋은 코드가 좋은 코드다
- Swift 3.0
- UIView
- EffectiveObjectiveC
- optional
- string
- Swfit
- applicationWillResignActive
- set
- ios
- 꺼내먹어요
- NSManagedObject
- Swift
- CIImage
- RunLoop
- Swift3
- NSManagedObjectContext
- delegate
- CGImage
- Swift 3
- docker
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |