如何检查CNContact swift中的联系人来源?

时间:2016-08-08 09:38:53

标签: ios swift google-contacts swift3 cncontact

在联系人应用程序中,有像“iCloud”,“yahoo”,“gmail”这样的群组。在swift中,是否可以仅从gmail源获取联系人?

3 个答案:

答案 0 :(得分:1)

经过测试的代码。希望它能解决你的问题...

   func getAppropriateName(for container: CNContainer?) -> String? {
        var name = ""
        if (container?.name == "Card") || container?.name == nil {
            name = "iCloud"
        }
        else if (container?.name == "Address Book") {
            name = "Google"
        }
        else if (container?.name == "Contacts") {
            name = "Yahoo"
        }
        else {
            name = "Facebook"
        }
        return name
    }

答案 1 :(得分:0)

iCloud / yahoo / gmail等是CNContainer。 Gmail / iCloud的类型为CNContainerTypeCardDAV。首先,您需要获取所有联系人,然后根据该联系人的CNContainerType过滤数组。但不幸的是,我们无法确定它是哪种CardDav,即iCloud / Gmail。

请在此处查看更多详情:How do we know which CNContainer represents iCloud?

答案 2 :(得分:0)

您可以通过查看此处的Contacts框架运行时标头来实现此目的:https://github.com/JaviSoto/iOS10-Runtime-Headers/tree/master/Frameworks/Contacts.framework

您可以通过performSelector消息给他们打电话。它有点乱,但有效。

一般来说,您需要做的是:

CNContactStore* store = [CNContactStore new];

// fetch accounts that sync contacts with your device (array of CNAccount)
// since CNAccount class isn't available by default, we treat it as NSObject for our puproses

NSArray* accounts = [store performSelector:@selector(accountsMatchingPredicate:error:) withObject:nil withObject:nil];

// you can iterate through this array, I just use first one for this example

NSObject* account = [accounts firstObject];

// get identifier of the account for NSPredicate we use next

NSString* accountId = [account performSelector:@selector(identifier)];

// Display name of the account (aka Yahoo, Gmail etc.)
NSString* accountName = [account performSelector:@selector(_cnui_displayName)];

// NSPredicate that help us to get corresponding CNContainer

NSPredicate* containerPredicate = [[CNContainer class] performSelector:@selector(predicateForContainersInAccountWithIdentifier:) withObject:accountId];

// Fetching CNContainer
CNContainer* container = [[store containersMatchingPredicate:containerPredicate error:nil] firstObject];

之后,所有关于CNContainers的一般用法。 希望它会有所帮助。

PS。它适用于iOS 10,对于将来应该检查Contacts.framework运行时更改的版本。

PPS。我没有检查swift,但也应该工作。

抱歉我的英文。 祝你好运:)