Xamarin.Tip – Read All Contacts in iOS 2.0

This is a second post to follow Xamarin.Tip – Read All Contacts in iOS to give a more efficient alternative to interacting with the CNContact API. Check out the change in the ContactService below! Using the EnumerateContacts ensures we get contacts from all groups including non standard groups like those brought from backups or iCloud integrated contacts. It is also a newer API call that has better performance.

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

iOS

Today we’ll look at getting all of the contacts in iOS and mapping them to a local shared model that any platform can ingest.

So let’s first define a simple model for our contact. This can have more models that are shared, but we will focus on the phone number and name for the sake of demonstrating.

PhoneContact.cs


    public class PhoneContact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }

        public string Name { get => $"{FirstName} {LastName}"; }

    }

Now let’s create a service in our iOS app project that uses the CNContact API. This will be responsible for getting all of the devices contacts (whether they have come from a back up, added, or are synced through iCloud).

The breakdown of this code can be found below.

ContactService.cs

    public class ContactService
    {
       public IEnumerable<PhoneContact> GetAllContacts()
        {
            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
            var contactList = new List<CNContact>();

            using (var store = new CNContactStore())
            {
                var request = new CNContactFetchRequest(keysTOFetch);
                store.EnumerateContacts(request, out error, new CNContactStoreListContactsHandler((CNContact contact, ref bool stop) => contactList.Add(contact)));
                
            }
            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;
        }
    
    }

Let’s breakdown what the code is doing here:

  1. Identify the properties of the contacts you want to grab – see keysToFetch
  2. Instantiate the CNContactStore and get all of the collections which will contain all of the contacts.
  3. Fetch all of the contacts from each container and add them to the master list.
  4. Loop over all of the contact data and add a new PhoneContact
    for each of the phone numbers they have. This could be done with giving a contact an IEnumerable PhoneNumbers rather than just one phone number, but in order to separate each phone number, that’s how we will do it.
  5. Return the formatted list of contacts/phone numbers

We can list this out in a UITableView, or in the case of the screenshot below, in a Xamarin.Forms ListView.

The last thing we need to do is make sure we have the permission to access the user’s contacts! We can do this by updating the info.plist with a Privacy - Contacts Usage Description property.

Screen Shot 2017-08-22 at 10.34.43 AM

Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

Simulator Screen Shot Aug 21, 2017, 11.20.32 AM.png

Next we’ll look at building this same type of ContactService for Android in order to be able to gather all of the contacts on the device and follow up with using both of these services in Xamarin.Forms to create a contact picker control!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisements

Xamarin.Tip – Read All Contacts in iOS

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

iOS

Today we’ll look at getting all of the contacts in iOS and mapping them to a local shared model that any platform can ingest.

So let’s first define a simple model for our contact. This can have more models that are shared, but we will focus on the phone number and name for the sake of demonstrating.

PhoneContact.cs


    public class PhoneContact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }

        public string Name { get => $"{FirstName} {LastName}"; }

    }

Now let’s create a service in our iOS app project that uses the CNContact API. This will be responsible for getting all of the devices contacts (whether they have come from a back up, added, or are synced through iCloud).

The breakdown of this code can be found below.

ContactService.cs

    public class ContactService
    {
        public IEnumerable<PhoneContact> GetAllContacts()
        {
            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>();

            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;
        }
    }

Let’s breakdown what the code is doing here:

  1. Identify the properties of the contacts you want to grab – see keysToFetch
  2. Instantiate the CNContactStore and get all of the collections which will contain all of the contacts.
  3. Fetch all of the contacts from each container and add them to the master list.
  4. Loop over all of the contact data and add a new PhoneContact
    for each of the phone numbers they have. This could be done with giving a contact an IEnumerable PhoneNumbers rather than just one phone number, but in order to separate each phone number, that’s how we will do it.
  5. Return the formatted list of contacts/phone numbers

We can list this out in a UITableView, or in the case of the screenshot below, in a Xamarin.Forms ListView.

The last thing we need to do is make sure we have the permission to access the user’s contacts! We can do this by updating the info.plist with a Privacy - Contacts Usage Description property.

Screen Shot 2017-08-22 at 10.34.43 AM

Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

Simulator Screen Shot Aug 21, 2017, 11.20.32 AM.png

Next we’ll look at building this same type of ContactService for Android in order to be able to gather all of the contacts on the device and follow up with using both of these services in Xamarin.Forms to create a contact picker control!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Borderless Inputs

I published multiple posts this week about creating Xamarin.Forms controls without borders using Custom renderers. This post is your one stop shop for all these posts. These are the controls that are used in my repository to create Material Design inputs in Xamarin.Forms that you can find here:
https://github.com/SuavePirate/SuaveControls.MaterialFormControls. These will be talked about in posts to come!
Check the borderless controls out here:

  1. Xamarin.Forms Borderless Entry
  2. Xamarin.Forms Borderless Picker
  3. Xamarin.Forms Borderless DatePicker
  4. Xamarin.Forms Borderless TimePicker
  5. Xamarin.Forms Borderless Editor

And check out how they look here:

BorderlessEntry


BorderlessEditor

BorderlessPicker

BorderlessDatePicker

BorderlessTimePicker

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Playing Audio Through the Earpiece in iOS

There is plenty of documentation from Xamarin on how to play audio files in our Xamarin.iOS apps (or Xamarin.Forms apps):

But none of these talk about piping the audio to either the speaker or the earpiece (the onboard one used for phone calls). Handling this logic is useful for applications that have a “voicemail” sort of feature or a real-time communications app. Here’s a brief bit of code that can handle playing an audio file through the speaker or through the earpiece:

AudioService.cs

 public class AudioService : IAudioService
    {
        public AudioService()
        {
        }

        public void PlaySoundThroughEarPiece(string fileName)
        {
            var session = AVAudioSession.SharedInstance();
            session.SetCategory(AVAudioSessionCategory.PlayAndRecord);
            session.SetActive(true);
            NSError error;
            var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
            player.Volume = 1.0f;
            player.Play();

        }

        public void PlaySoundThroughSpeaker(string fileName)
        {
            var session = AVAudioSession.SharedInstance();
            session.SetCategory(AVAudioSessionCategory.Playback);
            session.SetActive(true);
            NSError error;
            var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
            player.Volume = 1.0f;
            player.Play();
            
        }
    }

The key is calling the SetCategory with the appropriate AVAudioSessionCategory and setting the session to active before playing the sound through the AVAudioPlayer.

and you can call it like so:

var audioService = new AudioService();
audioService.PlaySoundThroughEarPiece("sample_sound.mp3");
audioService.PlaySoundThroughSpeaker("sample_sound.mp3");

Check out an example of this on my GitHub here in Xamarin.Forms: https://github.com/SuavePirate/XamarinEarpieceAudioTest

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Basics – Ad Hoc iOS Builds, Part 2a: Publishing in HockeyApp

Before Getting Started

Before learning how to upload your iOS builds to HockeyApp, be sure to check out Part 1 of this series: Xamarin.Basics – Ad Hoc iOS Builds, Part1: Certificates and Profiles to learn about the requirements for producing Ad Hoc builds that will be distributed in HockeyApp.

Quick Intro

Up to this point, we should have everything we need to build our iOS application in Release/Ad Hoc mode to produce an .ipa file. This output .ipa is what we will be uploading to HockeyApp and other distribution channels such as Mobile Center. It’s important to note that HockeyApp is actually on its way out the door and being booted by the new Visual Studio Mobile Center produced by Microsoft after acquiring HockeyApp and their team. At this point, Mobile Center is still in Preview, so if you’re looking for a production ready solution for the time being, stay here. If not, follow my next blog post (to be posted here) on doing this in Mobile Center.

Building

Now that we have our Distribution Certificate and Ad Hoc Provisioning Profile created in the Apple Developer Portal and downloaded on our Mac, we can move into Visual Studio and build our Application for Ad Hoc Release. The screenshots you’ll see below will be from Visual Studio 2017 on Windows, but the same principles apply to Visual Studio for Mac.

Ensure your Bundle Identifiers Match

In the Apple Developer portal, we created an App ID and in this definition, we set a Bundle Identifier. This ID needs to match the ID of our actual application. You can set the Bundle Identifier in the Info.plist file of your iOS project in Visual Studio.

Screen Shot 2017-07-12 at 1.54.00 PM

Set Build Configuration to Release – iPhone

Screen Shot 2017-07-12 at 2.07.06 PM

In order to build for iOS Ad Hoc distribution, you’ll need to build against an actual iOS device. Building for simulators does some things differently behind the scenes that makes it faster to install in a simulator. Since our app needs to run against devices, we need to build against a real device. We also need to build in Release mode since we shouldn’t be debugging an Ad Hoc build.

Double Check Your Bundle Signing

Before building, double check that your app is going to use the proper Signing Identity and Provisioning Profile. You can do this by opening the Properties (“Options” if your in VS for Mac) and go to the Bundle Signing tab. Here you can explicitly set a Profile and Certificate to use or let it automatically choose the profile and hope it works out.

Screen Shot 2017-07-12 at 2.12.12 PM.png

Build and Deploy

Now simply build and deploy your app by right clicking the project in the Solution Explorer and clicking the Deploy option.

Screen Shot 2017-07-12 at 2.21.49 PM

This will now create the .ipa file in your bin. Locate your .ipa at YOUR_IOS_PROJECT\bin\Ad-Hoc\YOUR_BUNDLE.ipa. This .ipa is what will be uploaded to HockeyApp and distributed.

Using HockeyApp

HockeyApp has some great getting started documentation for creating your app and also viewing crash reports etc. You can find that here: https://support.hockeyapp.net/kb.

We will focus on uploading a new build using the .ipa file we created. In order to do this, you will need to have created an account with HockeyApp and created an iOS Alpha or Beta application slot.

From here you can click on the Add Version button which will then prompt you to upload your .ipa file.

Screen Shot 2017-07-12 at 2.39.05 PMScreen Shot 2017-07-12 at 2.39.12 PM

Now you’ll be able to add some release notes to your version that is being uploaded. Then enable the people who are allowed to install your app and send them notifications.

Once this is done, your users whose devices are registered by their UDID to the Apple Developer Portal and the Provisioning Profile used will be able to download and install it through the HockeyApp mobile website!

With your users having their hands on the app, you’ll be able to view crash reports, respond to feedback and more through the HockeyApp portal!

Next Steps

Now that we’ve been able to manually upload builds to HockeyApp, we’ll be able to look at using Continuous Integration and Deployment to distribute our new versions as we commit our changes in the source code. James Montemagno has a great blog post in the official Xamarin blog here: https://blog.xamarin.com/continuous-integration-for-ios-apps-with-visual-studio-team-services/.

In a following post, we will look at the future of deploying our iOS applications internally by using the new Visual Studio Mobile Center.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

[Video] Xamarin.Basics – Ad Hoc iOS Builds, Part 1: Certificates and Profiles

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Basics – Ad Hoc iOS Builds, Part 1: Certificates and Profiles

For those who are newer to iOS application development and are trying to run their app on devices or deploy it to others’ devices, let me first offer you my condolences. Now let’s look at the overwhelming number of steps required to do a basic build on an iOS device!

Resources Required Before Starting

  1. A Mac. You can’t do this without an actual Mac device running OSX
  2. XCode installed on the Mac
  3. An Apple Developer license (read below)

Join the Apple Developer Program

In order to distribute apps, you’ll need to create certificates and profiles in the end. Before you can do that, you’ll need to join the Apple developer program for iOS. Keep in mind, this can take time (multiple days).

Head over to https://developer.apple.com/programs/ and click on the Enroll button.

apple_enroll

You’ll see an intimidating following something like this:

Enrolling as an Individual

If you are an individual or sole proprietor/single person business, sign in with your Apple ID to get started. You’ll need to provide basic personal information, including your legal name and address.

Enrolling as an Organization

If you’re enrolling your organization, you’ll need an Apple ID as well as the following to get started:

 
A D-U-N-S® Number

Your organization must have a D-U-N-S Number so that we can verify your organization’s identity and legal entity status. These unique nine-digit numbers are assigned by Dun & Bradstreet and are widely used as standard business identifiers. You can check to see if your organization already has a D-U-N-S Number and request one if necessary. They are free in most jurisdictions. Learn more

 
Legal Entity Status

Your organization must be a legal entity so that it can enter into contracts with Apple. We do not accept DBAs, fictitious businesses, trade names, or branches.

Legal Binding Authority

As the person enrolling your organization in the Apple Developer Program, you must have the legal authority to bind your organization to legal agreements. You must be the organization’s owner/founder, executive team member, senior project lead, or have legal authority granted to you by a senior employee.

Follow all the steps for either an individual or organization. PS. This costs about $100 (as of June 2017). Once you’ve submitted your enrollment application, an Apple employee will review your request and get back to you within 1-2 business days (usually) with your accepted (or declined) enrollment. Once this is done, you’ll be able to access the developer portal where you can add other members of your organization, manage certificates, apps, devices, and profiles.

Getting the Proper Requirements for Ad Hoc

Now that you can access the portal, go to the Developer portal and click on Account to sign in with your Apple ID.

After signing in, you’ll see some options on the left navigation bar. Click on Certificates, IDs, and Profiles

Components You Will Get From This Post

There are 4 major components you will need in order to be able to deploy an app to multiple devices:

  1. An App ID
  2. An Ad Hoc Certificate – created, downloaded, and installed on the machine.
  3. The UDIDs of every iOS device that will run the app
  4. A Provisioning Profile that combines all three things

Creating an App ID

In the developer portal Certificates, IDs, and Profiles section, click on App IDs from the left menu, then click the plus button in the top right:
Screen Shot 2017-06-21 at 10.33.47 AMScreen Shot 2017-06-21 at 10.23.59 AMScreen Shot 2017-06-21 at 10.24.04 AM

Then fill out the fields for Name and Bundle Identifier.
Screen Shot 2017-06-21 at 10.24.22 AMScreen Shot 2017-06-21 at 10.24.36 AM

Scroll on down and select the additional App Services this app will need to support:Screen Shot 2017-06-21 at 10.24.50 AM

Click Continue and you’ll be done creating your App ID and can continue to creating a certificate.

Creating a Distribution Certificate

Over in the left navigation, click on Certificates > Production then click the plus button in the top right:Screen Shot 2017-06-21 at 10.25.06 AMScreen Shot 2017-06-21 at 10.25.10 AM

In the Production select App Store and Ad Hoc, then scroll down to Continue:

Screen Shot 2017-06-21 at 10.25.20 AM

You’ll then see a page that explains how to create a Certificate Signing Request that is required to generate the Certificate. Click Continue, then in the Mac open the Keychain Access application.
Then from the Keychain Access menu, go to Certificate Assistant and Request a Certificate from a Certificate Authority:
cert_request

Fill out the form and save the request file locally:
Screen Shot 2017-06-21 at 10.26.09 AM

Take this newly saved file and go back to the Apple Developer Portal and upload it:

upload_cert

Click Continue and you’ll now be able to download the Certificate. Double click / open the newly downloaded certificate, and it will be installed into your keychain.

Important Notes About Certificates

Guess what! It gets more complicated and annoying!

Once you’ve created a certificate, you can ONLY USE IT on the machine that created the signing request due to the signing mechanism. In order to allow a user to use the certificate, you’ll need to export it to a .p12 file which is then signed by a new password. The other Mac user can then take that .p12 file and save it to their keychain using said password. We won’t go into depth about this process in this post, but perhaps in a follow-up.

Adding iOS Devices

In order to install an ad-hoc or non-App Store iOS app, the devices that will install and run the app need to be registered and eventually included in part of the build process. In the Apple Developer Portal we can add devices to our profile (up to 100 devices).

In the left navigation, click on Devices > All then once again click the plus button in the top right:Screen Shot 2017-06-21 at 10.26.56 AM

Give your new device a Name and then get the UDID of the device.

Getting the UDID of an iOS Device

Plug in your iOS device to your Mac and open iTunes if it doesn’t open automatically. In iTunes, click on the device button to get to the device details:Screen Shot 2017-06-21 at 11.50.49 AM.png

You’ll notice that there is no UDID field! Here’s the secret: click the device’s Serial Number to reveal the UDID:

Copy the UDID.

Back in the Apple Developer Portal add the UDID and click Continue to save the device.

Now that we have an App ID, Certificate, and our devices, the last step is to create a Provisioning Profile and install it on the Mac.

Creating an Ad Hoc Provisioning Profile

In the left navigation, click on Provisioning Profiles > Distribution and then the plus button in the top right.Screen Shot 2017-06-21 at 10.33.16 AM

Next you’ll be asked which type of Profile you want to create. Select Ad Hoc under the Distribution section.Screen Shot 2017-06-21 at 10.33.22 AM

Click Continue and you’ll then need to select which App ID this profile is for. In the dropdown, select the App ID you created:select_app_id

Click Continue and you’ll need to select the Distribution Certificate to associate with the profile. Select the certificate you just created:
Screen Shot 2017-06-21 at 10.33.50 AM

Click Continue and you’ll need to select the devices that are allowed to run this application built with this profile. Select the devices you added or want to enable:Screen Shot 2017-06-21 at 10.34.00 AM

Click Continue and give your profile a Nameprofile_preview
Click Continue and you can review the profile before generating it.

Click Generate and then Download the profile. Double-Click or open the newly downloaded profile and it will then be instlled into XCode.

Now with your certificate installed on the machine’s keychain and the profile installed into XCode, you’ll be able to build against iOS devices in Release. Doing this build will then generate an .ipa file. This file is what can be uploaded to Mobile Center, HockeyApp, or any other distribution channel you want to use.

Next Steps

In the next few blog posts, we’ll look at actually uploading a new build .ipa file to both HockeyApp and Mobile Center so that test users can download and install it on their devices. Stay tuned!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.