getting contacts in swift 3 not working

I'm trying to get contacts (swift 3) in ios 9

func getInnerContacts()-> Observable<[CNContact]>{
        return Observable<[CNContact]>.create({ (observer) -> Disposable in
            var contacts = [CNContact]()
            let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
            self.contactStore.requestAccess(for: .contacts, completionHandler: { (granted, error) -> Void in
                if granted {
                    let predicate = CNContact.predicateForContactsInContainer(withIdentifier: self.contactStore.defaultContainerIdentifier())
                    do {
                        contacts = try self.contactStore.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])

                        contacts = newContacts.filter({ (contact) -> Bool in
                            return !contact.phoneNumbers.isEmpty && contact.givenName != "" || !contact.phoneNumbers.isEmpty && contact.familyName != ""
                        })

                        observer.onNext(contacts)
                        observer.onCompleted()

                    }catch {
                        observer.onError(error)
                    }
                }
            })
            return Disposables.create()
        })
    }

but it doesn't work, moreover, I can't see permission alert. Before executing i first check the iOS version, like this:

if #available(iOS 10 , *){  

}else if #available(iOS 9, *){            

}

then i added permission tag Privacy - Contacts Usage Description into Info.plist file. This works fine in ios 10, any ideas how can I achieve this in ios 9

Upvotes: 0

Views: 1089

Answers (1)

Reddy
Reddy

Reputation: 19

It will work fine in Swift 3.

var store = CNContactStore()
var contacts = [CNContact]()

Try this in viewDidLoad():

let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactEmailAddressesKey, CNContactOrganizationNameKey, CNContactImageDataKey]

    let request = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor])

    do {
        try self.store.enumerateContacts(with: request) { contact, stop in

            self.contacts.append(contact)
        }

        DispatchQueue.main.async(execute: {
        for contact in self.contacts {
            print("contact:\(contact)")
            let firstName=String(format:"%@",contact.givenName)
           // print("first:\(firstName)")
            self.givenNameArray.append(firstName)
            let lastName=String(format:"%@",contact.familyName)
           // print("last:\(lastName)")
            self.familyNameArray.append(lastName)
            let comapny=String(format:"%@",contact.organizationName)
           // print("company:\(comapny)")
            self.organizationNameArray.append(comapny)
            //get all phone numbers
            // for ContctNumVar: CNLabeledValue in contact.phoneNumbers
            // {
            //  let MobNumVar  = (ContctNumVar.value ).value(forKey: "digits") as? String
            //  print("ph no:\(MobNumVar!)")

            // get one phone number
            let MobNumVar = (contact.phoneNumbers[0].value ).value(forKey: "digits") as! String
           // print("mob no:\(MobNumVar)")
            self.phonenosArray.append(MobNumVar)
            // get all emails
            // for ContctNumVar1: CNLabeledValue in contact.emailAddresses
            // {
            //   print("email \(ContctNumVar1.value(forKey: "value") as! String)")
            // }
            // get one email
            let email = (contact.emailAddresses[0]).value(forKey: "value") as! String
           // print("email:\(email)")
            self.emailsArray.append(email)

            let imagedat=contact.imageData
          //  print("image data:\(imagedat)")
            let image=UIImage(data: imagedat!)
           // print("image:\(image)")
            self.imagesArray.append(image!)
           }
        })


    } catch {
        print(error)
    }

Upvotes: 1

Related Questions