Пример #1
0
        public List <PhoneContactIOSModel> GetAllContacts()
        {
            var     keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses, CNContactKey.PhoneNumbers, CNContactKey.ThumbnailImageData };
            NSError error;

            CNContact[] contactList;
            var         ContainerId = new CNContactStore().DefaultContainerIdentifier;

            using (var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId))

                using (var store = new CNContactStore())
                {
                    contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out error);
                }
            var contacts = new List <PhoneContactIOSModel>();

            foreach (var item in contactList)
            {
                if (null != item && null != item.EmailAddresses)
                {
                    contacts.Add(new PhoneContactIOSModel
                    {
                        GivenName          = item.GivenName,
                        FamilyName         = item.FamilyName,
                        EmailId            = item.EmailAddresses.Select(m => m.Value.ToString()).FirstOrDefault(),
                        PhoneNumbers       = item.PhoneNumbers.Select(m => m.Value.StringValue).FirstOrDefault(),
                        ThumbnailImageData = item.ThumbnailImageData
                    });
                }
            }

            return(contacts);
        }
Пример #2
0
        public IEnumerable <CNContact> GetAllRaw(NSString[] keys)
        {
            List <CNContact> results = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out var error);

                if (error != null)
                {
                    throw new Exception($"iOS Exception: {error}");
                }

                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keys, out error);
                            results.AddRange(containerResults);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"DeviceContacts_iOS Error: {ex}");
                        // ignore missed contacts from errors
                    }
                }
            }

            return(results);
        }
Пример #3
0
        List <CNContact> GetIosContacts()
        {
            var result = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                NSError error;
                var     allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, _keys, out error);
                            result.AddRange(containerResults);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.HandleException(ex);
                    }
                }
            }

            return(result);
        }
Пример #4
0
        /// <summary>
        /// Gets contact in main thread
        /// !!!Not Recommended
        /// </summary>
        public IEnumerable <Contact> GetContactList(Func <Contact, bool> filter = null)
        {
            //try
            //{
            var     keysToFetch = new[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses, CNContactKey.PhoneNumbers, CNContactKey.ImageDataAvailable, CNContactKey.ThumbnailImageData };
            NSError error;
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type, you can specify that here
            var contactList = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("\n\n\n" + ex.ToString() + "\n\n\n");

                        if (ex.GetType() != typeof(NullReferenceException))
                        {
                            Debug.WriteLine(ex.ToString());
                        }
                        continue;
                    }
                }
            }
            //var contacts = new List<Contact>();

            var result = new List <Contact>();

            foreach (var item in contactList)
            {
                if (item.GivenName == null)
                {
                    continue;
                }
                Contact _contact = new Contact();


                if (filter != null && !filter(_contact))
                {
                    continue;
                }

                result.Add(_contact);
            }

            return(result);
        }
        public async Task <IEnumerable <PhoneContact> > GetAllContactsAsync()
        {
            var keysToFetch = new[]
            {
                CNContactKey.GivenName,
                CNContactKey.FamilyName,
                CNContactKey.PhoneNumbers
            };
            NSError error;
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type,
            // you can specify that here
            var contactList = new List <CNContact>();

            await Task.Run(() =>
            {
                using (var store = new CNContactStore())
                {
                    var allContainers = store.GetContainers(null, out error);
                    foreach (var container in allContainers)
                    {
                        try
                        {
                            using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                            {
                                var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                                contactList.AddRange(containerResults);
                            }
                        }
                        catch
                        {
                            // ignore missed contacts from errors
                        }
                    }
                }
            });

            var contacts = new List <PhoneContact>();

            foreach (var item in contactList)
            {
                var numbers = item.PhoneNumbers;
                if (numbers != null)
                {
                    foreach (var item2 in numbers)
                    {
                        contacts.Add(new PhoneContact
                        {
                            FirstName   = item.GivenName,
                            LastName    = item.FamilyName,
                            PhoneNumber = item2.Value.StringValue
                        });
                    }
                }
            }
            return(contacts);
        }
Пример #6
0
        public async Task <IEnumerable <PhoneContact> > GetAllContacts()
        {
            //Permission
            if (!(await PermissionGranting()))
            {
                return(new List <PhoneContact>());
            }

            //Contacts
            var keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses, CNContactKey.ThumbnailImageData };
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type, you can specify that here
            var contactList = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out NSError error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    }
                    catch (Exception e) { Console.WriteLine(e.Message); } // ignore missed contacts from errors
                }
            }
            var contacts = new List <PhoneContact>();

            foreach (var item in contactList)
            {
                var emails = item.EmailAddresses;
                if (emails != null)
                {
                    try
                    {
                        var stream = item.ThumbnailImageData?.AsStream();
                        contacts.Add(new PhoneContact
                        {
                            FirstName      = item.GivenName,
                            LastName       = item.FamilyName,
                            FullName       = $"{item.GivenName} {item.FamilyName}",
                            Email          = (emails.GetLength(0) > 0) ? emails[0].Value : String.Empty,
                            PhotoThumbnail = "ic_user"//Xamarin.Forms.ImageSource.FromStream(() => stream)
                        });
                    }
                    catch (Exception ex) { Console.WriteLine(ex.Message); }
                }
            }
            return(contacts);
        }
Пример #7
0
        public IEnumerable <Contact> GetContacts()
        {
            var keys        = CNContactFormatter.GetDescriptorForRequiredKeys(CNContactFormatterStyle.FullName);
            var keysToFetch = new [] {
                CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName,
                CNContactKey.EmailAddresses, CNContactKey.PhoneNumbers, CNContactKey.ImageData,
                CNContactKey.ImageDataAvailable, CNContactKey.ThumbnailImageData,
            };
            NSError error;

            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type, you can specify that here
            var contactList = new List <CNContact> ();

            using (var store = new CNContactStore()) {
                var allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier)) {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    } catch (Exception ex) {
                        continue;
                    }
                }
                foreach (var item in contactList)
                {
                    if (item.GivenName == null)
                    {
                        continue;
                    }
                    var image        = item.ImageDataAvailable ? CacheImage(item.ImageData) : null;
                    var thumb        = CacheImage(item.ThumbnailImageData);
                    var formatterKey = new [] { CNContactFormatter.GetDescriptorForRequiredKeys(CNContactFormatterStyle.FullName) };
                    var altItem      = store.GetUnifiedContact <ICNKeyDescriptor> (item.Identifier, formatterKey, out error);
                    var contact      = new Contact()
                    {
                        FirstName     = item.GivenName,
                        LastName      = item.FamilyName,
                        FullName      = CNContactFormatter.GetStringFrom(altItem, CNContactFormatterStyle.FullName),
                        ImagePath     = image,
                        ThumbnailPath = thumb
                    };
                    contact.Numbers.AddRange(ToPhoneNumbers(item.PhoneNumbers));

                    yield return(contact);
                }
            }
        }
Пример #8
0
        public IEnumerable <Contact> GetAllContacts()
        {
            var contacts = new List <Contact>();

            // Define fields to be searched
            var fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses, CNContactKey.Nickname, CNContactKey.ImageData, CNContactKey.PhoneNumbers };

            NSError error;

            store = new CNContactStore();
            if (CNContactStore.GetAuthorizationStatus(CNEntityType.Contacts) != CNAuthorizationStatus.Denied)
            {
                var cnContainers = store.GetContainers(null, out error);
                if (cnContainers != null)
                {
                    foreach (var container in cnContainers)
                    {
                        // Create predicate to locate requested contact
                        var predicate  = CNContact.GetPredicateForContactsInContainer(container.Identifier);
                        var cnContacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
                        if (CNContactStore.GetAuthorizationStatus(CNEntityType.Contacts) == CNAuthorizationStatus.Authorized)
                        {
                            foreach (var c in cnContacts)
                            {
                                var con = new Contact();
                                con.Email = new List <string>();
                                foreach (var email in c.EmailAddresses)
                                {
                                    con.Email.Add(email.ToString());
                                }
                                con.PhoneNumber = new List <string>();
                                foreach (var phone in c.PhoneNumbers)
                                {
                                    con.PhoneNumber.Add(phone.ToString());
                                }
                                con.ID          = c.Identifier;
                                con.FirsName    = c.GivenName;
                                con.LastName    = c.FamilyName;
                                con.ImageSource = c.ImageData != null?ImageSource.FromStream(() => c.ImageData.AsStream()) : null;

                                con.DisplayName = c.GivenName + " " + c.FamilyName;
                                con.NickName    = c.Nickname;
                                contacts.Add(con);
                            }
                        }
                    }
                }
            }
            return(contacts);
        }
Пример #9
0
        public Task <List <ContactModel> > GetContactListAsync()
        {
            var contactList = new List <ContactModel>();

            try
            {
                var keysToFetch = new[]
                {
                    CNContactKey.GivenName,
                    CNContactKey.FamilyName,
                    CNContactKey.PhoneNumbers
                };

                using (var store = new CNContactStore())
                {
                    var allContainers = store.GetContainers(null, out var _);

                    foreach (var container in allContainers)
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out _);

                            foreach (var contact in containerResults)
                            {
                                var name = string.Concat(contact.GivenName, " ", contact.FamilyName);

                                for (var i = 0; i < contact.PhoneNumbers.Length; i++)
                                {
                                    var number = contact.PhoneNumbers[i];

                                    contactList.Add(new ContactModel
                                    {
                                        Name   = string.Concat(name, i > 0 ? $" {i + 1}" : ""),
                                        Number = number.Value.StringValue
                                    });
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"--- Error: {e.StackTrace}");
            }

            return(Task.FromResult(contactList));
        }
Пример #10
0
        public string sendMsg()
        {
            var     keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers };
            NSError error;

            bool check = false;

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            foreach (var item in containerResults)
                            {
                                var num = item.PhoneNumbers;
                                foreach (var cn in num)
                                {
                                    string mob = cn.Value.StringValue;
                                    if (mob == ProfileContentView.phone)
                                    {
                                        check = true;
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            if (check == false)
            {
                var store       = new CNContactStore();
                var contact     = new CNMutableContact();
                var cellPhone   = new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.Mobile, new CNPhoneNumber(ProfileContentView.phone));
                var phoneNumber = new[] { cellPhone };
                contact.PhoneNumbers = phoneNumber;
                contact.GivenName    = ProfileContentView.name;
                var saveRequest = new CNSaveRequest();
                saveRequest.AddContact(contact, store.DefaultContainerIdentifier);
            }
            return("1");
        }
        //========================================================================================================================================
        //  PUBLIC OVERRIDES
        //========================================================================================================================================
        //========================================================================================================================================
        //  PUBLIC METHODS
        //========================================================================================================================================

        /// <summary>
        /// Creates a list of all contacts in the users Contacts book.
        /// </summary>
        /// <returns>The fake object list context.</returns>
        public List <CNContact> initFakeObjectListContext()
        {
            var ContactList = new List <CNContact> ();

            if (access)
            {
                var predicate = CNContact.GetPredicateForContactsInContainer(store.DefaultContainerIdentifier);
                var keys      = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers };

                Foundation.NSError error;
                ContactList = store.GetUnifiedContacts(predicate, keys, out error).ToList();
            }

            return(ContactList);
        }
Пример #12
0
        public List <Contact> GetContactList()
        {
            var     keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers, CNContactKey.EmailAddresses };
            NSError error;
            var     contactList = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    }
                    catch (Exception)
                    {
                        // ignore missed contacts from errors
                        throw;
                    }
                }
            }
            var contacts = new List <Contact>();


            foreach (var item in contactList)
            {
                var numbers = item.PhoneNumbers;
                if (numbers != null)
                {
                    foreach (var item2 in numbers)
                    {
                        contacts.Add(new Contact
                        {
                            Name   = item.GivenName,
                            Number = item2.Value.StringValue,
                        });
                    }
                }
            }
            return(contacts);
        }
Пример #13
0
        private static IEnumerable <CNContact> ReadFromContainer(
            IEnumerable <NSString> keysToFetch,
            CNContainer container,
            CNContactStore store)
        {
            try
            {
                using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                {
                    return(store.GetUnifiedContacts(predicate, keysToFetch.ToArray(), out _));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"\n\n\n{ex}\n\n\n");
            }

            return(null);
        }
Пример #14
0
        public Task <IEnumerable <Contact> > GetAllAsync(CancellationToken cancellationToken)
        {
            var keys = new[]
            {
                CNContactKey.Identifier,
                CNContactKey.NamePrefix,
                CNContactKey.GivenName,
                CNContactKey.MiddleName,
                CNContactKey.FamilyName,
                CNContactKey.NameSuffix,
                CNContactKey.EmailAddresses,
                CNContactKey.PhoneNumbers,
                CNContactKey.Type
            };

            var store      = new CNContactStore();
            var containers = store.GetContainers(null, out _);

            if (containers == null)
            {
                return(Task.FromResult <IEnumerable <Contact> >(Array.Empty <Contact>()));
            }

            return(Task.FromResult(GetEnumerable()));

            IEnumerable <Contact> GetEnumerable()
            {
                foreach (var container in containers)
                {
                    using var pred = CNContact.GetPredicateForContactsInContainer(container.Identifier);
                    var contacts = store.GetUnifiedContacts(pred, keys, out var error);
                    if (contacts == null)
                    {
                        continue;
                    }

                    foreach (var contact in contacts)
                    {
                        yield return(ConvertContact(contact));
                    }
                }
            }
        }
Пример #15
0
        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task <IEnumerable <Contact> > GetContacts()
        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            var resultingContacts = new List <Contact>();

            var keysToFetch = new[] {
                #pragma warning disable XI0002 // Notifies you from using newer Apple APIs when targeting an older OS version
                CNContactKey.PhoneNumbers,
                CNContactKey.GivenName,
                CNContactKey.EmailAddresses,
                CNContactKey.FamilyName
                #pragma warning restore XI0002 // Notifies you from using newer Apple APIs when targeting an older OS version
            };

            var containerId = new CNContactStore().DefaultContainerIdentifier;

            using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
            {
                CNContact[] contactList;
                using (var store = new CNContactStore())
                {
                    contactList = store.GetUnifiedContacts(predicate, keysToFetch, out var error);
                }

                resultingContacts.AddRange(from item in contactList
                                           where item?.EmailAddresses != null
                                           select new Contact
                {
                    Number    = item.PhoneNumbers.Any() ? item.PhoneNumbers[0]?.Value?.ValueForKey(new Foundation.NSString("stringValue"))?.ToString() : null,
                    Name      = item.GivenName + " " + item.FamilyName,
                    FirstName = item.GivenName,
                    LastName  = item.FamilyName,
                    Email     = item.EmailAddresses.Select(m => m.Value.ToString()).FirstOrDefault()
                });
            }

            resultingContacts.Sort((x, y) => string.Compare(x.FirstName, y.FirstName));

            return(resultingContacts);
        }
Пример #16
0
        public ObservableCollection <Contact> GetContactList()
        {
            ObservableCollection <Contact> list = new ObservableCollection <Contact>();

            NSError error;
            var     containerId = new CNContactStore().DefaultContainerIdentifier;
            var     predicate   = CNContact.GetPredicateForContactsInContainer(containerId);

            // 取得したいフィールドを設定
            var fetchKeys = new NSString[]
            {
                CNContactKey.GivenName,
                CNContactKey.FamilyName,
                CNContactKey.PhoneticGivenName,
                CNContactKey.PhoneticFamilyName,
                CNContactKey.EmailAddresses,
                CNContactKey.PhoneNumbers
            };

            //全ての連絡先を取得する
            var store    = new CNContactStore();
            var contacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);

            // 名前、かな、電話番号、メールアドレスを取得
            if (contacts != null && contacts.Length > 0)
            {
                foreach (var contact in contacts)
                {
                    list.Add(new Contact()
                    {
                        Name  = contact.FamilyName + " " + contact.GivenName,
                        Kana  = contact.PhoneticFamilyName + " " + contact.PhoneticGivenName,
                        Tel   = GetTel(contact.PhoneNumbers),
                        Email = GetEmail(contact.EmailAddresses)
                    });
                }
            }

            return(list);
        }
        private void PopulateContactList(List <PersonContact> contacts)
        {
            CNContact[] contactList = new CNContact[0];
            var         keysTOFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers };
            var         containerId = new CNContactStore().DefaultContainerIdentifier;

            NSError containerError = new NSError();
            var     containers     = new CNContactStore().GetContainers(null, out containerError);

            foreach (var item in containers)
            {
                containerId = item.Identifier;


                NSError unifiedContanctError = new NSError();
                using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
                    using (var store = new CNContactStore())
                    {
                        contactList = store.GetUnifiedContacts(predicate, keysTOFetch, out unifiedContanctError);
                    }

                int index = 0;
                foreach (var contact in contactList)
                {
                    if (null != item && contact.PhoneNumbers.Length > 0)
                    {
                        contacts.Add(new PersonContact
                        {
                            ContactID    = index,
                            GivenName    = contact.GivenName,
                            FamilyName   = contact.FamilyName,
                            PhoneNumbers = contact.PhoneNumbers
                        });
                        index++;
                    }
                }
            }
        }
        public IList <Contact> GetContactList()
        {
            try
            {
                var     keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses };
                NSError error;
                //var containerId = new CNContactStore().DefaultContainerIdentifier;
                // using the container id of null to get all containers.
                // If you want to get contacts for only a single container type, you can specify that here
                var contactList = new List <CNContact>();
                using (var store = new CNContactStore())
                {
                    var allContainers = store.GetContainers(null, out error);
                    foreach (var container in allContainers)
                    {
                        try
                        {
                            using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                            {
                                var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                                contactList.AddRange(containerResults);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("\n\n\n" + ex.ToString() + "\n\n\n");

                            if (ex.GetType() != typeof(NullReferenceException))
                            {
                                Debug.WriteLine(ex.ToString());
                            }
                            continue;
                        }
                    }
                }
                var contacts = new List <Contact>();

                foreach (var item in contactList)
                {
                    if (item.GivenName == null)
                    {
                        continue;
                    }
                    Contact _contact = new Contact();
                    _contact.Name = item.GivenName + " " + item.FamilyName;

                    if (item.PhoneNumbers != null)
                    {
                        foreach (var number in item.PhoneNumbers)
                        {
                            _contact.Number = number?.Value?.ToString();
                            _contact.Numbers.Add(number?.Value?.ToString());
                        }
                    }

                    if (item.EmailAddresses != null)
                    {
                        foreach (var email in item.EmailAddresses)
                        {
                            _contact.Email = email?.Value?.ToString();
                            _contact.Emails.Add(email?.Value?.ToString());
                        }
                    }
                    contacts.Add(_contact);
                }
                return(contacts);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\n\n\n" + ex.ToString() + "\n\n\n");
                return(new List <Contact>());
            }
        }
Пример #19
0
        public List <ContactInfo> GetContactInfo()
        {
            var keysToFetch = new[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers, CNContactKey.PostalAddresses };
            //var containerId = new CNContactStore().DefaultContainerIdentifier;
            // using the container id of null to get all containers.
            // If you want to get contacts for only a single container type, you can specify that here
            var contactList = new List <CNContact>();

            using (var store = new CNContactStore())
            {
                var allContainers = store.GetContainers(null, out NSError error);
                foreach (var container in allContainers)
                {
                    try
                    {
                        using (var predicate = CNContact.GetPredicateForContactsInContainer(container.Identifier))
                        {
                            var containerResults = store.GetUnifiedContacts(predicate, keysToFetch, out error);
                            contactList.AddRange(containerResults);
                        }
                    }
                    catch
                    {
                        // ignore missed contacts from errors
                    }
                }
            }

            var contacts = new List <ContactInfo>();

            foreach (var item in contactList)
            {
                ContactInfo info = new ContactInfo
                {
                    Name = item.GivenName + " " + item.FamilyName
                };
                info.Name = info.Name.Trim();
                if (item.PhoneNumbers != null && item.PhoneNumbers.Length != 0)
                {
                    List <PhonesSave> phones = new List <PhonesSave>();
                    foreach (var i in item.PhoneNumbers)
                    {
                        string label = i.Label.Substring(4);
                        label = label.Remove(label.Length - 4);
                        phones.Add(new PhonesSave {
                            Label = label, Phone = i.Value.StringValue
                        });
                    }
                    info.Phones = JsonConvert.SerializeObject(phones.ToArray());
                }
                else
                {
                    info.Phones = "{}";
                }
                if (item.PostalAddresses != null && item.PostalAddresses.Length != 0)
                {
                    List <AddressSave> address = new List <AddressSave>();
                    foreach (var i in item.PostalAddresses)
                    {
                        string s = i.Value.Country;
                        s += " " + i.Value.State;
                        s += " " + i.Value.City;
                        s += " " + i.Value.Street;
                        s += " " + i.Value.PostalCode;
                        string label = i.Label.Substring(4);
                        label = label.Remove(label.Length - 4);
                        address.Add(new AddressSave {
                            Address = s, Label = label
                        });
                    }

                    info.Addresses = JsonConvert.SerializeObject(address.ToArray());
                }
                else
                {
                    info.Phones = "{}";
                }
                contacts.Add(info);
            }

            return(contacts);
        }
Пример #20
0
        public List <Contacto> GetLista()
        {
            Contacto c;

            lsc.Clear();
            try
            {
                Version ver = new Version(UIDevice.CurrentDevice.SystemVersion);
                if (ver.Major <= 8)
                {
                    NSError err;
                    var     iPhoneAddressBook = ABAddressBook.Create(out err);
                    var     authStatus        = ABAddressBook.GetAuthorizationStatus();
                    if (authStatus != ABAuthorizationStatus.Authorized)
                    {
                        iPhoneAddressBook.RequestAccess(delegate(bool granted, NSError error)
                        {
                            if (granted)
                            {
                                ABPerson[] myContacts = iPhoneAddressBook.GetPeople();
                                string phone          = string.Empty;
                                foreach (ABPerson contact in myContacts)
                                {
                                    ABMultiValue <string> phs = contact.GetPhones();
                                    if (phs.Count() > 0)
                                    {
                                        foreach (var stel in phs)
                                        {
                                            c = new Contacto()
                                            {
                                                Name   = contact.FirstName + " " + contact.LastName,
                                                Number = stel.Value,                                                 //phs.First().Value,
                                                Photo  = (contact.HasImage ? GetBitmap(contact.Image) : null),
                                            };
                                            lsc.Add(c);
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        ABPerson[] myContacts = iPhoneAddressBook.GetPeople();
                        string     phone      = string.Empty;
                        foreach (ABPerson contact in myContacts)
                        {
                            ABMultiValue <string> phs = contact.GetPhones();
                            if (phs.Count() > 0)
                            {
                                foreach (var stel in phs)
                                {
                                    c = new Contacto()
                                    {
                                        Name   = contact.FirstName + " " + contact.LastName,
                                        Number = stel.Value,                                         //phs.First().Value,
                                        Photo  = (contact.HasImage ? GetBitmap(contact.Image) : null),
                                    };
                                    lsc.Add(c);
                                }
                            }
                        }
                    }
                }
                if (ver.Major >= 9)
                {
                    //ios 9
                    var     store = new CNContactStore();
                    NSError error;
                    var     fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers, CNContactKey.ThumbnailImageData };
                    string  contid    = store.DefaultContainerIdentifier;
                    var     predicate = CNContact.GetPredicateForContactsInContainer(contid);
                    var     contacts  = store.GetUnifiedContacts(predicate, fetchKeys, out error);
                    foreach (CNContact cc in contacts)
                    {
                        for (int i = 0; i < cc.PhoneNumbers.Count(); i++)
                        {
                            Contacto ct = new Contacto()
                            {
                                Id     = cc.Identifier,
                                Name   = (!string.IsNullOrEmpty(cc.GivenName) ? cc.GivenName : "") + (!string.IsNullOrEmpty(cc.FamilyName) ? " " + cc.FamilyName : ""),
                                Number = (cc.PhoneNumbers[i] != null ? cc.PhoneNumbers[i].Value.StringValue : ""),
                                Photo  = (cc.ThumbnailImageData != null ? GetBitmap(cc.ThumbnailImageData) : null),
                            };
                            lsc.Add(ct);
                        }
                    }

                    /*lsc = contacts.Select(x => new Contacto()
                     * {
                     *      Id = x.Identifier,
                     *      Name = (!string.IsNullOrEmpty(x.GivenName) ? x.GivenName : "") + (!string.IsNullOrEmpty(x.FamilyName) ? " " + x.FamilyName : ""),
                     *      Number = (x.PhoneNumbers.FirstOrDefault() != null ? x.PhoneNumbers.FirstOrDefault().Value.StringValue : ""),
                     *      Photo = (x.ThumbnailImageData != null ? GetBitmap(x.ThumbnailImageData) : null),
                     * }).ToList();*/
                }
            }
            catch (Exception e)
            {
            }
            return(lsc);
        }