I am trying to save a phone number to the local device in MAUI by Conditional Compilation
.
Below is my code:
#if ANDROID
using Android.App;
using Android.Content;
using Android.OS;
using Android.Provider;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using MyApp.Droid.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#elif IOS
using AddressBook;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using UIKit;
using MyApp.iOS.Services;
#endif
namespace MyApp.Renderers
{
public class SaveContact
{
public void SaveContactToPhoneBook(string Name, string Number, string Email)
{
#if ANDROID
var activity = Android.App.Application.Context as Activity;
var intent = new Intent(Intent.ActionInsert).SetFlags(ActivityFlags.ClearTask);
intent.SetType(ContactsContract.Contacts.ContentType);
intent.PutExtra(ContactsContract.Intents.Insert.Name, Name);
intent.PutExtra(ContactsContract.Intents.Insert.Phone, Number);
intent.PutExtra(ContactsContract.Intents.Insert.Email, Email);
activity.StartActivity(intent);
#elif IOS
ABAddressBook ab = new ABAddressBook();
ABPerson p = new ABPerson();
p.FirstName = Name;
ABMutableMultiValue<string> phones = new ABMutableStringMultiValue();
phones.Add(Number, ABPersonPhoneLabel.Mobile);
p.SetPhones(phones);
ABMutableDictionaryMultiValue addresses = new ABMutableDictionaryMultiValue();
NSMutableDictionary a = new NSMutableDictionary();
addresses.Add(a, new NSString("Home"));
p.SetAddresses(addresses);
ab.Add(p);
ab.Save();
#endif
}
}
}
Then from my contacts save page:
SaveContact saveContact = new SaveContact();
saveContact.SaveContactToPhoneBook("", phone, "");//passing name, phone and email
I am getting exception for this from both Android and iOS platforms.
Android Exception:
System.NullReferenceException: Object reference not set to an instance of an object. at MyProject.Renderers.SaveContact.SaveContactToPhoneBook(String Name, String Number, String Email) in E:\My Projects\MAUI\MyProject-maui\MyProject\Renderers\SaveContact.cs:line 43 [SurfaceComposerClient] XDR setRegion is not supported 0xb4000075d1bc0cf0, 1, 0
iOS Exception:
CoreFoundation.CFException: The operation couldn’t be completed. (ABAddressBookErrorDomain error 1.) at AddressBook.ABAddressBook.Add(ABRecord ) at MyProject.Renderers.SaveContact.SaveContactToPhoneBook(String Name, String Number, String Email) in /Users/MyCompany/Projects/MyProject-maui/MyProject/Renderers/SaveContact.cs:line 55
The codes I have used are from Xamarin Forms Dependency Service
and I changed it to Conditional Compilation
for MAUI integration.