コード例 #1
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");
        }
コード例 #2
0
        public void SaveContact(ContactModel contact)
        {
            var store      = new CNContactStore();
            var iosContact = new CNMutableContact();

            List <CNLabeledValue <CNPhoneNumber> > phoneNumbers = new List <CNLabeledValue <CNPhoneNumber> >();
            List <CNLabeledValue <NSString> >      emails       = new List <CNLabeledValue <NSString> >();
            List <CNLabeledValue <NSString> >      websites     = new List <CNLabeledValue <NSString> >();

            foreach (PhoneField phoneField in contact.PhoneNumbers)
            {
                phoneNumbers.Add(new CNLabeledValue <CNPhoneNumber>(PhoneNumberTypeToKey(phoneField.Type), new CNPhoneNumber(phoneField.Number)));
            }

            foreach (EmailField emailField in contact.Emails)
            {
                emails.Add(new CNLabeledValue <NSString>(EmailTypeToKey(emailField.Type), new NSString(emailField.Email)));
            }

            foreach (ContactField websiteField in contact.Websites)
            {
                websites.Add(new CNLabeledValue <NSString>(CNLabelKey.UrlAddressHomePage, new NSString(websiteField.Text)));
            }

            iosContact.PhoneNumbers     = phoneNumbers.ToArray();
            iosContact.FamilyName       = contact.LastName;
            iosContact.GivenName        = contact.FirstName;
            iosContact.OrganizationName = !string.IsNullOrEmpty(contact.Company.Text) ? contact.Company.Text : string.Empty;
            iosContact.EmailAddresses   = emails.ToArray();
            iosContact.UrlAddresses     = websites.ToArray();

            if (!string.IsNullOrEmpty(contact.ProfileImage))
            {
                iosContact.ImageData = NSData.FromFile(contact.ProfileImage);
            }

            var saveRequest = new CNSaveRequest();

            saveRequest.AddContact(iosContact, store.DefaultContainerIdentifier);
            if (store.ExecuteSaveRequest(saveRequest, out NSError error))
            {
                Console.WriteLine("New contact saved");
            }
            else
            {
                Console.WriteLine("Save error: {0}", error);
            }
        }
コード例 #3
0
ファイル: Utilities.cs プロジェクト: artemy0/Quiz
        public static CNMutableContact ToCNMutableContact(this Contact contact)
        {
            if (contact == null)
            {
                return(null);
            }

            CNMutableContact nativeContact = new CNMutableContact();

            if (contact.FirstName != null)
            {
                nativeContact.GivenName = NSString.StringWithUTF8String(contact.FirstName);
            }

            if (contact.MiddleName != null)
            {
                nativeContact.MiddleName = NSString.StringWithUTF8String(contact.MiddleName);
            }

            if (contact.LastName != null)
            {
                nativeContact.FamilyName = NSString.StringWithUTF8String(contact.LastName);
            }

            if (contact.Company != null)
            {
                nativeContact.OrganizationName = NSString.StringWithUTF8String(contact.Company);
            }


            if (contact.Birthday != null)
            {
                nativeContact.Birthday = contact.Birthday.Value.ToNSDateComponents();
            }

            nativeContact.EmailAddresses = ToCNCotactEmails(contact.Emails);
            nativeContact.PhoneNumbers   = ToCNContactPhoneNumbers(contact.PhoneNumbers);

            if (contact.Photo != null)
            {
                byte[] rawData = TextureUtilities.EncodeAsByteArray(contact.Photo, ImageFormat.PNG);
                nativeContact.ImageData = NSData.DataWithBytes(rawData, (uint)rawData.Length);
            }

            return(nativeContact);
        }
コード例 #4
0
 void ShowUnknownPersonViewController()
 {
     using (var unknowContact = new CNMutableContact()) {
         try
         {
             var unknownContactVC = CNContactViewController.FromUnknownContact(unknowContact);
             unknownContactVC.ContactStore  = new CNContactStore();
             unknownContactVC.AllowsActions = true;
             unknownContactVC.AlternateName = "John Appleseed";
             unknownContactVC.Title         = "John Appleseed";
             unknownContactVC.Message       = "Company, Inc";
             NavigationController.PushViewController(unknownContactVC, true);
         }
         catch (Exception)
         {
             var alert = UIAlertController.Create("Error", "Could not create unknown user.", UIAlertControllerStyle.Alert);
             alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, null));
             PresentViewController(alert, true, null);
         }
     }
 }
コード例 #5
0
        public int WriteContact(Contact contact)
        {
            var contactToAdd = new CNMutableContact();

            contactToAdd.GivenName = contact.FirstName;
            var phoneNumber = new CNLabeledValue <CNPhoneNumber>(label: CNLabelKey.Home, value: new CNPhoneNumber(stringValue: contact.Number));

            contactToAdd.PhoneNumbers = new [] { phoneNumber };
            var store       = new CNContactStore();
            var saveRequest = new CNSaveRequest();

            saveRequest.AddContact(contactToAdd, null);
            var error = new NSError();

            try
            {
                store.ExecuteSaveRequest(saveRequest, out error);
                return(0);
            }
            catch
            {
                return(1);
            }
        }
コード例 #6
0
ファイル: IOSContactsProvider.cs プロジェクト: artemy0/Quiz
        public string AddContact(Contact contact)
        {
            try
            {
                CNContactStore contactStore = new CNContactStore();
                CNSaveRequest  saveRequest  = new CNSaveRequest();

                CNMutableContact nativeContact = contact.ToCNMutableContact();
                saveRequest.AddContactToContainerWithIdentifier(nativeContact, null);

                NSError saveError;
                bool    executeSuccess = contactStore.ExecuteSaveRequest(saveRequest, out saveError);

                return(executeSuccess
                    ? null
                    : saveError != null
                        ? saveError.LocalizedDescription
                        : ExecuteSaveRequestFailedMessage);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
コード例 #7
0
        public void Properties()
        {
            using (var contact = new CNMutableContact()) {
                Assert.IsNull(contact.Birthday, "Birthday");
                Assert.AreEqual(0, contact.ContactRelations.Length, "ContactRelations");
                Assert.AreEqual(CNContactType.Person, contact.ContactType, "ContactType");
                Assert.AreEqual(0, contact.Dates.Length, "Dates");
                Assert.AreEqual(string.Empty, contact.DepartmentName, "DepartmentName");
                Assert.AreEqual(0, contact.EmailAddresses.Length, "EmailAddresses");
                Assert.AreEqual(string.Empty, contact.FamilyName, "FamilyName");
                Assert.AreEqual(string.Empty, contact.GivenName, "GivenName");
                Assert.AreNotEqual(string.Empty, contact.Identifier, "Identifier");
                Assert.IsNull(contact.ImageData, "ImageData");
                Assert.IsFalse(contact.ImageDataAvailable, "ImageDataAvailable");
                Assert.AreEqual(0, contact.InstantMessageAddresses.Length, "InstantMessageAddresses");
                Assert.AreEqual(string.Empty, contact.JobTitle, "JobTitle");
                Assert.AreEqual(string.Empty, contact.MiddleName, "MiddleName");
                Assert.AreEqual(string.Empty, contact.NamePrefix, "NamePrefix");
                Assert.AreEqual(string.Empty, contact.NameSuffix, "NameSuffix");
                Assert.AreEqual(string.Empty, contact.Nickname, "Nickname");
                Assert.IsNull(contact.NonGregorianBirthday, "NonGregorianBirthday");
                Assert.AreEqual(string.Empty, contact.Note, "Note");
                Assert.AreEqual(string.Empty, contact.OrganizationName, "OrganizationName");
                Assert.AreEqual(0, contact.PhoneNumbers.Length, "PhoneNumbers");
                Assert.AreEqual(string.Empty, contact.PhoneticFamilyName, "PhoneticFamilyName");
                Assert.AreEqual(string.Empty, contact.PhoneticGivenName, "PhoneticGivenName");
                Assert.AreEqual(string.Empty, contact.PhoneticMiddleName, "PhoneticMiddleName");
                Assert.AreEqual(0, contact.PostalAddresses.Length, "PostalAddresses");
                Assert.AreEqual(string.Empty, contact.PreviousFamilyName, "PreviousFamilyName");
                Assert.AreEqual(0, contact.SocialProfiles.Length, "SocialProfiles");
                Assert.IsNull(contact.ThumbnailImageData, "ThumbnailImageData");
                Assert.AreEqual(0, contact.UrlAddresses.Length, "UrlAddresses");

                contact.Birthday = new NSDateComponents()
                {
                    Year = 1980
                };
                Assert.AreEqual(1980, contact.Birthday.Year, "Birthday");

                contact.ContactRelations = new CNLabeledValue <CNContactRelation> [] {
                    new CNLabeledValue <CNContactRelation> ("label", new CNContactRelation("relation"))
                };
                Assert.AreEqual(1, contact.ContactRelations.Length, "ContactRelations");

                contact.ContactType = CNContactType.Organization;
                Assert.AreEqual(CNContactType.Organization, contact.ContactType, "ContactType");

                contact.Dates = new CNLabeledValue <NSDateComponents> [] {
                    new CNLabeledValue <NSDateComponents> ("label", new NSDateComponents()
                    {
                        Month = 6
                    })
                };
                Assert.AreEqual(1, contact.Dates.Length, "Dates");

                contact.DepartmentName = "department";
                Assert.AreEqual("department", contact.DepartmentName, "DepartmentName");

                contact.EmailAddresses = new CNLabeledValue <NSString> [] {
                    new CNLabeledValue <NSString> ("label", (NSString)"*****@*****.**")
                };
                Assert.AreEqual(1, contact.EmailAddresses.Length, "EmailAddresses");

                contact.FamilyName = "familyName";
                Assert.AreEqual("familyName", contact.FamilyName, "FamilyName");

                contact.GivenName = "givenName";
                Assert.AreEqual("givenName", contact.GivenName, "GivenName");

                Assert.AreNotEqual(string.Empty, contact.Identifier, "Identifier");

                contact.ImageData = new NSData();
                Assert.IsNotNull(contact.ImageData, "ImageData");
                Assert.IsFalse(contact.ImageDataAvailable, "ImageDataAvailable");

                contact.InstantMessageAddresses = new CNLabeledValue <CNInstantMessageAddress> [] {
                    new CNLabeledValue <CNInstantMessageAddress> ("label", new CNInstantMessageAddress("user", "service")),
                };
                Assert.AreEqual(1, contact.InstantMessageAddresses.Length, "InstantMessageAddresses");

                contact.JobTitle = "title";
                Assert.AreEqual("title", contact.JobTitle, "JobTitle");

                contact.MiddleName = "middleName";
                Assert.AreEqual("middleName", contact.MiddleName, "MiddleName");

                contact.NamePrefix = "namePrefix";
                Assert.AreEqual("namePrefix", contact.NamePrefix, "NamePrefix");

                contact.NameSuffix = "nameSuffix";
                Assert.AreEqual("nameSuffix", contact.NameSuffix, "NameSuffix");

                contact.Nickname = "nickname";
                Assert.AreEqual("nickname", contact.Nickname, "Nickname");

                contact.NonGregorianBirthday = new NSDateComponents()
                {
                    Year = 2099,
                };
                Assert.AreEqual(2099, contact.NonGregorianBirthday.Year, "NonGregorianBirthday");

                contact.Note = "note";
                Assert.AreEqual("note", contact.Note, "Note");

                contact.OrganizationName = "organizationName";
                Assert.AreEqual("organizationName", contact.OrganizationName, "OrganizationName");

                contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber> [] {
                    new CNLabeledValue <CNPhoneNumber> ("label", new CNPhoneNumber("123-345-456"))
                };
                Assert.AreEqual(1, contact.PhoneNumbers.Length, "PhoneNumbers");

                contact.PhoneticFamilyName = "phoneticFamilyName";
                Assert.AreEqual("phoneticFamilyName", contact.PhoneticFamilyName, "PhoneticFamilyName");

                contact.PhoneticGivenName = "phoneticGivenName";
                Assert.AreEqual("phoneticGivenName", contact.PhoneticGivenName, "PhoneticGivenName");

                contact.PhoneticMiddleName = "phoneticMiddleName";
                Assert.AreEqual("phoneticMiddleName", contact.PhoneticMiddleName, "PhoneticMiddleName");

                contact.PostalAddresses = new CNLabeledValue <CNPostalAddress> [] {
                    new CNLabeledValue <CNPostalAddress> ("label", new CNMutablePostalAddress()
                    {
                        Street = "my Street",
                    })
                };
                Assert.AreEqual(1, contact.PostalAddresses.Length, "PostalAddresses");

                contact.PreviousFamilyName = "previousFamilyName";
                Assert.AreEqual("previousFamilyName", contact.PreviousFamilyName, "PreviousFamilyName");

                contact.SocialProfiles = new CNLabeledValue <CNSocialProfile> [] {
                    new CNLabeledValue <CNSocialProfile> ("label", new CNSocialProfile("url", "username", "useridentifier", "service"))
                };
                Assert.AreEqual(1, contact.SocialProfiles.Length, "SocialProfiles");

                contact.UrlAddresses = new CNLabeledValue <NSString> [] {
                    new CNLabeledValue <NSString> ("label", (NSString)"*****@*****.**")
                };
                Assert.AreEqual(1, contact.UrlAddresses.Length, "UrlAddresses");
            }
        }
コード例 #8
0
        public bool AddContacts(QContact qc)
        {
            Console.WriteLine("export contacts ios");

            var contact = new CNMutableContact();

            // Set standard properties
            contact.GivenName  = PreventNull(qc.FirstName);
            contact.FamilyName = PreventNull(qc.LastName);


            // Add email addresses
            var homeEmail = new CNLabeledValue <NSString>(CNLabelKey.Home, new NSString(PreventNull(qc.Email)));
            var email     = new[] { homeEmail };

            contact.EmailAddresses = email;

            // Add work address
            var workAddress = new CNMutablePostalAddress()
            {
                Street = PreventNull(qc.Addr)
            };

            contact.PostalAddresses = new[] { new CNLabeledValue <CNPostalAddress>(CNLabelKey.Work, workAddress) };

            // ADD BIRTHday
            string[] birth = PreventNull(qc.Birthday.ToString("MM/dd/yyyy")).Split('/');
            if (birth.Length == 3)
            {
                var birthday = new NSDateComponents()
                {
                    Month = int.Parse(birth[0]),
                    Day   = int.Parse(birth[1]),
                    Year  = int.Parse(birth[2])
                };
                contact.Birthday = birthday;
            }

            // add company
            contact.OrganizationName = PreventNull(qc.Company);

            // add others-> fb
            StringBuilder sb = new StringBuilder();

            sb.Append("Facebook:").Append(PreventNull(qc.Facebook)).Append(", Instagram:").Append(PreventNull(qc.Instagram))
            .Append(", Linkedin:").Append(PreventNull(qc.LinkedIn)).Append(", Skype:").Append(PreventNull(qc.Skype))
            .Append(", Twitter:").Append(PreventNull(qc.Twitter));
            contact.Note = sb.ToString();

            // add url
            var url   = new CNLabeledValue <NSString>(CNLabelKey.UrlAddressHomePage, new NSString(PreventNull(qc.URL)));
            var myUrl = new[] { url };

            contact.UrlAddresses = myUrl;

            //mobile
            var cellPhone =
                new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.Mobile, new CNPhoneNumber(PreventNull(qc.Mobile)));
            //var phoneNumber = new[] { cellPhone };
            //contact.PhoneNumbers = phoneNumber;

            //home phone
            var homePhone =
                new CNLabeledValue <CNPhoneNumber>("HOME", new CNPhoneNumber(PreventNull(qc.HomePhone)));

            //work phone
            var workPhone =
                new CNLabeledValue <CNPhoneNumber>("WORK", new CNPhoneNumber(PreventNull(qc.WorkPhone)));

            //homefax
            var homeFax =
                new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.HomeFax, new CNPhoneNumber(PreventNull(qc.HomeFax)));

            //workFax
            var workFax =
                new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.WorkFax, new CNPhoneNumber(PreventNull(qc.WorkFax)));
            var phoneNumber = new[] { cellPhone, homePhone, workPhone, homeFax, workFax };

            contact.PhoneNumbers = phoneNumber;

            // Save new contact
            var store       = new CNContactStore();
            var saveRequest = new CNSaveRequest();

            saveRequest.AddContact(contact, store.DefaultContainerIdentifier);

            NSError error;

            if (store.ExecuteSaveRequest(saveRequest, out error))
            {
                Console.WriteLine("New contact saved");
                return(true);
            }
            else
            {
                Console.WriteLine("Save error: {0}", error);
                return(false);
            }
        }
コード例 #9
0
		void ShowUnknownPersonViewController ()
		{
			using (var unknowContact = new CNMutableContact()) {
				try
				{
					var unknownContactVC = CNContactViewController.FromUnknownContact(unknowContact);
					unknownContactVC.ContactStore = new CNContactStore();
					unknownContactVC.AllowsActions = true;
					unknownContactVC.AlternateName = "John Appleseed";
					unknownContactVC.Title = "John Appleseed";
					unknownContactVC.Message = "Company, Inc";
					NavigationController.PushViewController(unknownContactVC, true);
				}
				catch (Exception)
				{
					var alert = UIAlertController.Create("Error", "Could not create unknown user.", UIAlertControllerStyle.Alert);
					alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, null));
					PresentViewController(alert, true, null);
				}
			}
		}
コード例 #10
0
        public static async void CreateContact(object sender, EventArgs e)
        {
            var     store = new CNContactStore();
            NSError error;

            if (CNContactStore.GetAuthorizationStatus(CNEntityType.Contacts) == CNAuthorizationStatus.Authorized)
            {
                CNContact currentUser = null;
                var       predicate   = CNContact.GetPredicateForContacts("Appleseed");
                var       fetchKeys   = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName };
                NSError   cError;
                var       contacts = store.GetUnifiedContacts(predicate, fetchKeys, out cError);
                for (int i = 0; i < contacts.Count(); i++)
                {
                    if (contacts[i].GivenName == App.contactuser.FirstName && contacts[i].FamilyName == App.contactuser.LastName)
                    {
                        currentUser = contacts[i];
                    }
                }


                // Found?
                if (currentUser != null)
                {
                    bool k = await App.Current.MainPage.DisplayAlert("Exists", "Requested contact already exists...", "Edit", "OK");

                    if (k)
                    {
                        personViewController = CNContactViewController.FromContact(currentUser);
                        var done = new UIBarButtonItem(UIBarButtonSystemItem.Done);
                        done.Clicked += (s, ea) =>
                        {
                            personViewController.DismissViewController(false, null);
                        };
                        personViewController.NavigationItem.LeftBarButtonItem = done;

                        navController.PushViewController(personViewController, true);
                        UIApplication.SharedApplication.KeyWindow.RootViewController.ShowViewController(navController, null);
                    }
                }
                else
                {
                    var contact = new CNMutableContact();

                    contact.GivenName  = App.contactuser.FirstName;
                    contact.FamilyName = App.contactuser.LastName;

                    // Add email addresses
                    var email = new CNLabeledValue <NSString>(CNLabelKey.Home, new NSString(App.contactuser.email));
                    contact.EmailAddresses = new CNLabeledValue <NSString>[] { email };

                    // Add phone numbers
                    var cellPhone = new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.iPhone, new CNPhoneNumber(App.contactuser.phoneNumber));
                    contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber>[] { cellPhone };
                    // Save new contact
                    var _store      = new CNContactStore();
                    var saveRequest = new CNSaveRequest();
                    saveRequest.AddContact(contact, _store.DefaultContainerIdentifier);

                    NSError cerror;
                    if (store.ExecuteSaveRequest(saveRequest, out cerror))
                    {
                        personViewController = CNContactViewController.FromContact(contact);
                        var done = new UIBarButtonItem(UIBarButtonSystemItem.Done);
                        done.Clicked += (s, ea) =>
                        {
                            personViewController.DismissViewController(false, null);
                        };
                        personViewController.NavigationItem.LeftBarButtonItem = done;
                        navController.PushViewController(personViewController, true);
                        UIApplication.SharedApplication.KeyWindow.RootViewController.ShowViewController(navController, null);
                    }
                    else
                    {
                        Console.WriteLine("Save error: {0}", cerror);
                    }
                }
            }
            else
            {
                store.RequestAccess(CNEntityType.Contacts, RequestAccepted);
            }
        }
コード例 #11
0
        private void PerformContactAction(UITableViewCell selectedCell)
        {
            if (selectedCell == createNewContactCell)
            {
                var contactViewController = CNContactViewController.FromNewContact(null);
                contactViewController.Delegate = this;
                base.NavigationController.PushViewController(contactViewController, true);
            }

            else if (selectedCell == createNewContactExistingDataCell)
            {
                var contact = new CNMutableContact
                {
                    FamilyName = Name.Family,
                    GivenName  = Name.Given,
                };

                contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber>[]
                {
                    new CNLabeledValue <CNPhoneNumber>(PhoneNumber.IPhone, new CNPhoneNumber(PhoneNumber.IPhone)),
                    new CNLabeledValue <CNPhoneNumber>(PhoneNumber.Mobile, new CNPhoneNumber(PhoneNumber.Mobile))
                };

                var homeAddress = new CNMutablePostalAddress
                {
                    Street     = Address.Street,
                    City       = Address.City,
                    State      = Address.State,
                    PostalCode = Address.PostalCode
                };
                contact.PostalAddresses = new CNLabeledValue <CNPostalAddress>[] { new CNLabeledValue <CNPostalAddress>(CNLabelKey.Home, homeAddress) };

                //Erstelle einen Kontakt-View-Controller mit unserem Kontakt
                var contactViewController = CNContactViewController.FromNewContact(contact);
                contactViewController.Delegate = this;
                base.NavigationController.PushViewController(contactViewController, true);
            }

            else if (selectedCell == editContactCell)
            {
                var contact = new CNMutableContact();

                contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber>[] { new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.iPhone, new CNPhoneNumber(PhoneNumber.Mobile)) };
                var homeAddress = new CNMutablePostalAddress()
                {
                    Street     = Address.Street,
                    City       = Address.City,
                    State      = Address.State,
                    PostalCode = Address.PostalCode
                };
                contact.PostalAddresses = new CNLabeledValue <CNPostalAddress>[] { new CNLabeledValue <CNPostalAddress>(CNLabelKey.Home, homeAddress) };

                var contactViewController = CNContactViewController.FromUnknownContact(contact);
                contactViewController.AllowsEditing = true;
                contactViewController.ContactStore  = new CNContactStore();
                contactViewController.Delegate      = this;

                base.NavigationController.PushViewController(contactViewController, true);
            }

            else if (selectedCell == displayEditCell)
            {
                var name = $"{Name.Given} {Name.Family}";
                FetchContact(name, (contacts) =>
                {
                    if (contacts.Any())
                    {
                        var contactViewController           = CNContactViewController.FromContact(contacts[0]);
                        contactViewController.AllowsEditing = true;
                        contactViewController.AllowsActions = true;
                        contactViewController.Delegate      = this;

                        var highlightedPropertyIdentifiers = contacts[0].PhoneNumbers.FirstOrDefault()?.Identifier;
                        if (!string.IsNullOrEmpty(highlightedPropertyIdentifiers))
                        {
                            contactViewController.HighlightProperty(new NSString("phoneNumbers"), highlightedPropertyIdentifiers);
                        }
                        else
                        {
                            this.ShowAlert($"Could not find {name} in Contacts.");
                        }
                    }
                });
            }
        }
コード例 #12
0
        private void PerformContactAction(UITableViewCell selectedCell)
        {
            if (selectedCell == this.createNewContactCell)
            {
                // Create an empty contact view controller.
                var contactViewController = CNContactViewController.FromNewContact(null);
                // Set its delegate.
                contactViewController.Delegate = this;
                // Push it using the navigation controller.
                base.NavigationController.PushViewController(contactViewController, true);
            }
            // Called when users tap "Create New Contact With Existing Data" in the UI.
            // Create and launch a contacts view controller with pre - filled fields.
            else if (selectedCell == this.createNewContactExistingData)
            {
                var contact = new CNMutableContact
                {
                    // Given and family names.
                    FamilyName = Name.Family,
                    GivenName  = Name.Given,
                };

                // Phone numbers.
                contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber>[]
                {
                    new CNLabeledValue <CNPhoneNumber>(PhoneNumber.IPhone,
                                                       new CNPhoneNumber(PhoneNumber.IPhone)),
                    new CNLabeledValue <CNPhoneNumber>(PhoneNumber.Mobile,
                                                       new CNPhoneNumber(PhoneNumber.Mobile))
                };

                // Postal address.
                var homeAddress = new CNMutablePostalAddress
                {
                    Street     = Address.Street,
                    City       = Address.City,
                    State      = Address.State,
                    PostalCode = Address.PostalCode,
                };

                contact.PostalAddresses = new CNLabeledValue <CNPostalAddress>[] { new CNLabeledValue <CNPostalAddress>(CNLabelKey.Home, homeAddress) };

                // Create a contact view controller with the above contact.
                var contactViewController = CNContactViewController.FromNewContact(contact);
                // Set its delegate.
                contactViewController.Delegate = this;
                // Push it using the navigation controller.
                base.NavigationController.PushViewController(contactViewController, true);
            }
            // Called when users tap "Edit Unknown Contact" in the UI.
            // The view controller displays some contact information that you can either add to an existing contact or use them to create a new contact.
            else if (selectedCell == this.editContactCell)
            {
                var contact = new CNMutableContact();

                // Phone number.
                contact.PhoneNumbers = new CNLabeledValue <CNPhoneNumber>[] { new CNLabeledValue <CNPhoneNumber>(CNLabelPhoneNumberKey.iPhone, new CNPhoneNumber(PhoneNumber.Mobile)) };

                // Postal address.
                var homeAddress = new CNMutablePostalAddress()
                {
                    Street     = Address.Street,
                    City       = Address.City,
                    State      = Address.State,
                    PostalCode = Address.PostalCode,
                };

                contact.PostalAddresses = new CNLabeledValue <CNPostalAddress>[] { new CNLabeledValue <CNPostalAddress>(CNLabelKey.Home, homeAddress) };

                // Create a view controller that allows editing.
                var contactViewController = CNContactViewController.FromUnknownContact(contact);
                contactViewController.AllowsEditing = true;
                contactViewController.ContactStore  = new CNContactStore();
                contactViewController.Delegate      = this;

                // Push the unknown contact in the view controler.
                base.NavigationController.PushViewController(contactViewController, true);
            }
            // Called when users tap "Display and Edit Contact" in the UI.
            // Searches for the contact specified whose last name and first name are respectively specified by contact.family and contact.given
            else if (selectedCell == this.displayEditCell)
            {
                var name = $"{Name.Given} {Name.Family}";
                this.FetchContact(name, (contacts) =>
                {
                    if (contacts.Any())
                    {
                        var contactViewController           = CNContactViewController.FromContact(contacts[0]);
                        contactViewController.AllowsEditing = true;
                        contactViewController.AllowsActions = true;
                        contactViewController.Delegate      = this;

                        /*
                         *  Set the view controller's highlightProperty if
                         *  highlightedPropertyIdentifier exists. Thus, ensuring
                         *  that the contact's phone number specified by
                         *  highlightedPropertyIdentifier will be highlighted in the
                         *  UI.
                         */

                        var highlightedPropertyIdentifiers = contacts[0].PhoneNumbers.FirstOrDefault()?.Identifier;
                        if (!string.IsNullOrEmpty(highlightedPropertyIdentifiers))
                        {
                            contactViewController.HighlightProperty(new NSString("phoneNumbers"), highlightedPropertyIdentifiers);
                        }

                        // Show the view controller.
                        base.NavigationController.PushViewController(contactViewController, true);
                    }
                    else
                    {
                        this.ShowAlert($"Could not find {name} in Contacts.");
                    }
                });
            }
        }