眺めて覚える C# Xamarin Forms(14) 連絡先 参照

#今回は、連絡先のアクセスがテーマです。
##連絡先をアプリに読み込む締めには、許可が必要になります。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/3e0a1d49-da3b-7f64-fb1c-829c9959235d.png)
#プロジェクト作成の手順
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/64561c07-0b10-23f7-e6fd-d2608a017e9a.png)
#Propertiesに変更を加えます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/e0b2a839-cdaf-41ce-2a4c-c0e8a57c7e1a.png)
##必要があれば書き込み許可を与えます。
###マニフェストには、下記のように自動的に追加されます。
```AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.projectcontact" android:installLocation="auto">
	<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
	<application android:label="ProjectContact.Android"></application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.READ_CONTACTS" />
	<uses-permission android:name="android.permission.WRITE_CONTACTS" />
</manifest>
```
#MainActivity.csに許可のためのルーチンを追加します。①②
```MainActivity.cs
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
//許可ダイアログ用①
using Android.Support.V4.Content;
using Android.Support.V4.App;
using Android;

namespace ProjectContact.Droid
{
    [Activity(Label = "ProjectContact", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            // 許可ダイアログのために追加②
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadContacts) != (int)Permission.Granted)
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadContacts }, 0);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
```

#依存関係にNugetで追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/a0498671-e68f-f93e-4540-469b02e8f39f.png)
##Xamarin.Forms.Contactsを追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/bc8a1668-5e64-879b-4c0f-7e9f34a2fdb3.png)

#以下の例は、xamlを用いずプログラム的にデザインを作成しています。
```MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ProjectContact
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
#pragma warning disable CS4014 // この呼び出しは待機されなかったため、現在のメソッドの実行は呼び出しの完了を待たずに続行されます
            GetContacs();
        }
        class MyContact
        {
            public string Name { get; set; } = "";
            public string Email { get; set; } = "";
            public string Number { get; set; } = "";
        }
        async Task GetContacs()
        {
            var contacts = await Plugin.ContactService.CrossContactService.Current.GetContactListAsync();
            var list = new List<MyContact>();
            foreach (var x in contacts)
            {
                list.Add(new MyContact
                {
                    Name = x.Name ?? "",
                    Email = x.Email ?? "",
                    Number = (x.Numbers.Count > 0) ? x.Numbers[0] : ""
                });
            }
            var tmp = new DataTemplate(() =>
            {
                var grid = new Grid() { Margin = 0, BackgroundColor = Color.Black };
                grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                var name = new Label { TextColor = Color.White, FontSize = 18 };
                name.SetBinding(Label.TextProperty, "Name");
                var email = new Label() { TextColor = Color.White };
                email.SetBinding(Label.TextProperty, "Email");
                var number = new Label() { TextColor = Color.White };
                number.SetBinding(Label.TextProperty, "Number");
                grid.Children.Add(name, 0, 0);
                grid.Children.Add(number, 0, 1);
                grid.Children.Add(email, 1, 1);
                return new ViewCell { View = grid };
            });
            var lv = new ListView() { ItemsSource = list, ItemTemplate = tmp };
            Content = new Xamarin.Forms.ScrollView() { Margin = 1, Orientation = ScrollOrientation.Vertical, Content = lv };
        }

    }
}

```
#実行結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/398c2941-1821-f9bf-f3b1-4f7e75eee1ad.png)