我是Swift 3語言的新手,我想從手機中獲取數組中的聯繫人,然後存儲在sqliteDB中。請幫忙。使用Swift 3從手機和商店獲取聯繫人到sqliteDB
我看到了一個Swift 2.1的老教程,但所有這些方法都被棄用,我嘗試了很多CNContacts
,但這對我沒有幫助。
我也試過堆棧溢出的這種聯繫,但沒有得到任何幫助:
Fetching all contacts in ios Swift?
我是Swift 3語言的新手,我想從手機中獲取數組中的聯繫人,然後存儲在sqliteDB中。請幫忙。使用Swift 3從手機和商店獲取聯繫人到sqliteDB
我看到了一個Swift 2.1的老教程,但所有這些方法都被棄用,我嘗試了很多CNContacts
,但這對我沒有幫助。
我也試過堆棧溢出的這種聯繫,但沒有得到任何幫助:
Fetching all contacts in ios Swift?
我剛剛工作的一個類似的問題,所以我會給你我的代碼。我從幾個不同的線索中找到它(包括this)。我們的要求是,剛剛從所有聯繫人獲得單獨的電話號碼,並把它變成一個String數組,但你可以很容易地修改此做多:
func getContacts(){
contactStore.requestAccess(for: .contacts, completionHandler: {
granted, error in
var contacts: [CNContact] = {
let contactStore = CNContactStore()
//Change keys here to retreive more than just the phone number of the contact
let keysToFetch = [CNContactPhoneNumbersKey]
// Get all the containers
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containers(matching: nil)
} catch {
print("Error fetching containers")
}
var results: [CNContact] = []
// Iterate all containers and append their contacts to our results array
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
do {
let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as [CNKeyDescriptor])
results.append(contentsOf: containerResults)
for phone in results{
for labeledValue in phone.phoneNumbers{
self.phoneNumbersArray.append(labeledValue.value.stringValue)
}
}
} catch {
print("Error fetching results for container")
}
}
return results
}()
self.getFriendsFromPhoneNumbers()
})
}
此經過的所有容器和返回CNObjects數組(只有裏面的電話號碼,但你可以通過更改鍵來獲得更多),然後遍歷數組中的每個聯繫人和標籤,只將電話號碼作爲字符串插入到電話號碼數組中。
它適合我。但我應該寫什麼來獲取firstName和familyName? –
你必須使用更多的鍵,如:[CNContactGivenNameKey,CNContactFamilyNameKey] –
我已經改變了密鑰,但我必須寫在這個for循環 ///////////////// ////// for phonesValue phone.phoneNumbers { print(labeledValue.value.stringValue) } –
你能告訴我們你在那之前已經嘗試過了嗎? – Randy
對不起,我撤銷了我的代碼,因爲它沒有工作。 –
你真的想把你的聯繫人存儲在sqlite數據庫嗎?你有一些很好的選擇。我通常使用[Realm](https://realm.io/),但也可以使用[CoreData](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index。 html?utm_source = iosstash.io) 並取得聯繫人,請檢查[這個答案](http://stackoverflow.com/a/34095632/3844377) – Randy