Skip to content

Commit 04352ac

Browse files
committed
expand contact fetching example
1 parent abafd8a commit 04352ac

File tree

1 file changed

+36
-10
lines changed

1 file changed

+36
-10
lines changed

bk2ch18p713addressBookNew/ch31p973addressBook/ViewController.swift

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,23 +54,49 @@ class ViewController : UIViewController, CNContactPickerDelegate, CNContactViewC
5454
//
5555

5656
@IBAction func doFindMoi (sender:AnyObject!) {
57-
5857
CNContactStore().requestAccessForEntityType(.Contacts) {
5958
ok, err in
6059
guard ok else {
6160
print("not authorized")
6261
return
6362
}
63+
var which : Int {return 2} // 1 or 2
6464
do {
65-
let pred = CNContact.predicateForContactsMatchingName("Matt")
66-
var matts = try CNContactStore().unifiedContactsMatchingPredicate(pred, keysToFetch: [
67-
CNContactFamilyNameKey, CNContactGivenNameKey
68-
])
69-
matts = matts.filter{$0.familyName == "Neuburg"}
70-
guard var moi = matts.first else {
71-
print("couldn't find myself")
72-
return
65+
var premoi : CNContact!
66+
switch which {
67+
case 1:
68+
let pred = CNContact.predicateForContactsMatchingName("Matt")
69+
var matts = try CNContactStore().unifiedContactsMatchingPredicate(pred, keysToFetch: [
70+
CNContactFamilyNameKey, CNContactGivenNameKey
71+
])
72+
matts = matts.filter{$0.familyName == "Neuburg"}
73+
guard var moi = matts.first else {
74+
print("couldn't find myself")
75+
return
76+
}
77+
premoi = moi
78+
case 2:
79+
let pred = CNContact.predicateForContactsMatchingName("Matt")
80+
let req = CNContactFetchRequest(keysToFetch: [
81+
CNContactFamilyNameKey, CNContactGivenNameKey
82+
])
83+
req.predicate = pred
84+
var matt : CNContact? = nil
85+
try CNContactStore().enumerateContactsWithFetchRequest(req) {
86+
con, stop in
87+
if con.familyName == "Neuburg" {
88+
matt = con
89+
stop.memory = true
90+
}
91+
}
92+
guard var moi = matt else {
93+
print("couldn't find myself")
94+
return
95+
}
96+
premoi = moi
97+
default:break
7398
}
99+
var moi = premoi
74100
print(moi)
75101
if moi.isKeyAvailable(CNContactEmailAddressesKey) {
76102
print(moi.emailAddresses)
@@ -91,8 +117,8 @@ class ViewController : UIViewController, CNContactPickerDelegate, CNContactViewC
91117
print(error)
92118
}
93119
}
94-
95120
}
121+
96122

97123
@IBAction func doCreateSnidely (sender:AnyObject!) {
98124
let snidely = CNMutableContact()

0 commit comments

Comments
 (0)