如何使用 swift 从 iPhone 联系人中检索电子邮件?

How to retrieve emails from iPhone Contacts using swift?

我是 swift 的新手。我使用 APAdressBook Framework 在 iPhone 中检索联系人。在 IOS 8.4 之前一切正常,但在模拟器和 iPhone 设备的 IOS 9 中检查时,它无法访问联系人甚至它没有显示警报消息,比如您想访问联系人吗?任何人都可能遇到此类问题,如果是,请给我您宝贵的答案?

Apple Inc. 从 iOS9 引入 Contacts.framework。所以,最好使用此框架来检索联系人。

这是从通讯录应用程序中获取电子邮件或整个联系人的方法。

Contacts.framework 添加到您的项目。

创建或添加类型为 header 的新文件并命名为 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"))
        }