0
我是新来的swift。我使用APAdressBook Framework来检索iPhone中的联系人。每件事情都可以正常工作到IOS 8.4,但是在模拟器和iPhone设备的IOS 9中检查时,它不会访问联系人,甚至不会显示警报消息,如您想访问任何联系人如果是的话,可以面对这种类型的问题请给我你的宝贵答案?如何使用swift从iPhone联系人中检索电子邮件?
我是新来的swift。我使用APAdressBook Framework来检索iPhone中的联系人。每件事情都可以正常工作到IOS 8.4,但是在模拟器和iPhone设备的IOS 9中检查时,它不会访问联系人,甚至不会显示警报消息,如您想访问任何联系人如果是的话,可以面对这种类型的问题请给我你的宝贵答案?如何使用swift从iPhone联系人中检索电子邮件?
Apple Inc.从iOS 9引入Contacts.framework
。因此,最好使用此框架来检索联系人。
以下是从联系人应用获取电子邮件或整个联系人的方法。
将Contacts.framework
添加到您的项目中。
创建或添加类型头文件的新文件并给出如yourProjectName-Bridging-Header.h
这样的名称将#import <Contacts/Contacts.h>
语句写入文件并保存并设置来自构建设置的此文件的适当路径。
现在创建方法
func getAllContacts() {
let status = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts) as CNAuthorizationStatus
if status == CNAuthorizationStatus.Denied {
let alert = UIAlertController(title:nil, message:"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts", preferredStyle:UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil))
self.presentViewController(alert, animated:true, completion:nil)
return
}
let store = CNContactStore()
store.requestAccessForEntityType(CNEntityType.Contacts) { (granted:Bool, error:NSError?) -> Void in
if !granted {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
// user didn't grant access;
// so, again, tell user here why app needs permissions in order to do it's job;
// this is dispatched to the main queue because this request could be running on background thread
})
return
}
let arrContacts = NSMutableArray() // Declare this array globally, so you can access it in whole class.
let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName)])
do {
try store.enumerateContactsWithFetchRequest(request, usingBlock: { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
let arrEmail = contact.emailAddresses as NSArray
if arrEmail.count > 0 {
let dict = NSMutableDictionary()
dict.setValue((contact.givenName+" "+contact.familyName), forKey: "name")
let emails = NSMutableArray()
for index in 0...arrEmail.count {
let email:CNLabeledValue = arrEmail.objectAtIndex(index) as! CNLabeledValue
emails .addObject(email.value as! String)
}
dict.setValue(emails, forKey: "email")
arrContacts.addObject(dict) // Either retrieve only those contact who have email and store only name and email
}
arrContacts.addObject(contact) // either store all contact with all detail and simplifies later on
})
} catch {
return;
}
}
}
调用此方法,你想self.getAllContacts()
而当你想要检索
for var index = 0; index < self.arrContacts.count; ++index {
let dict = self.arrContacts[index] as! NSDictionary
print(dict.valueForKey("name"))
print(dict.valueForKey("email"))
}