Posted by on Mar 8, 2016 in #iOSDev, #Office365Dev | 0 comments

If you haven’t heard, there is an easy way to call a great amount of Microsoft APIs – using one single endpoint. This endpoint, so called the Microsoft Graph (https://graph.microsoft.io/) lets you access everything from data, to intelligence and insights powered by the Microsoft cloud.

No longer will you need to keep track of different endpoints and separate tokens in your solutions – how great is that? This post is an introductory part of getting started with the Microsoft Graph. For changes in the Microsoft Graph, head to: https://graph.microsoft.io/changelog

This blog post demonstrates how to register your application in Azure AD, which is needed when calling the Microsoft Graph. We will use the Microsoft Graph SDK for iOS (https://github.com/OfficeDev/Microsoft-Graph-SDK-iOS) and build a simple iOS application using the new Swift language (https://developer.apple.com/swift/). In the application we will send ourselves a mail. The objective is to get familiar with the Microsoft Graph and its possibilities.

app

Be aware, the Microsoft Graph SDK for iOS is still in preview. Read more about the conditions at: https://github.com/OfficeDev/Microsoft-Graph-SDK-iOS

The blog post is divided into multiple steps and should be followed in a chronological order. These are the included steps:

1.1 Register the application in Azure AD
1.2 Configure the application in Azure AD
2.1 Create the project
2.2 Add the dependencies
2.3 Create the bridging header
3.1 Add the MailClient class
3.2 Add the initializer
3.3 Add the getGraphServiceUrl function
3.4 Add the signInWithCallback function
3.5 Add the getUserWithCallback function
3.6 Add the createRecipientWithAddress function
3.7 Add the createBodyWithContent function
3.8 Add the createMessageWithSubject function
3.9 Add the sendMailWithMessage function
3.10 Add the sendMeWithCallback function
3.11 Configure ADAL with your Azure AD application
4.1 Update the UI

Short of time and just want the final sample? Clone this repository (https://github.com/simonjaeger/PnP/tree/msgraph-ios-samples) and open the Xcode workspace file: /Samples/MicrosoftGraph.iOS.Swift.SendMail/MSGraph.MailClient.xcworkspace.

Prerequisites

Xcode 7: https://developer.apple.com/xcode/
CocoaPods: https://cocoapods.org/
Office 365 Developer Tenant: http://dev.office.com/devprogram/
Azure subscription for the Office 365 Developer Tenant (a trial is sufficient)

Step 1.1: Register the application in Azure AD

The first thing that we need to do is to register our application in Azure AD. This is how can acquire an access token for the Microsoft Graph (on behalf of the user).

Make sure that you have all of the required prerequisites before getting into this step.

1. Head to the current Azure portal and sign in with a user in your Office 365 Developer Tenant at: https://manage.windowsazure.com/
2. In the left menu, choose on Active Directory to list your Azure AD.

3. Click on your Azure AD in the Directory tab section.

4. Click on Applications in the tab menu.
5. Click on the Add button at the bottom to register a new Azure AD application.

6. Choose on Add an application my organization is developing in the dialog that shows up.
7. Name your application “MicrosoftGraph.iOS.Swift.SendMail” and select Native Client Application. Proceed by clicking the continue button down at the bottom.

azureadapp

8. Enter “https://MicrosoftGraph.iOS.Swift.SendMail/” as the Redirect URI. Click on the check button down below to complete the wizard.

azureadapp2

Step 1.2: Configure the application in Azure AD

We need to configure the application in Azure AD to be able to request the Microsoft Graph as a resource. This is done by adding the Microsoft Graph as an application, along with a set of permissions.

1. Click on the Configure tab in the Azure AD application page.

configureapp
2. Scroll down to the bottom to the Permissions to other applications section and click on the Add application button.
3. Show Microsoft Apps and add the Microsoft Graph.
4. Save your changes by clicking the check button at the bottom.

5. Click on Delegated permissions and pick the Send mail as a user permission.

6. Save your configuration by clicking the Save button at the bottom.

Step 2.1: Create the project

Now let’s create the iOS application project in Xcode.

1. Open the File menu. Select New and finally click on the Project… button.
2. In the iOS tab, select the Application to display the available templates for iOS.
3. Click on Single View Application and finally the Next button.

projecttype

4. Enter “MSGraph.MailClient” as the Product Name.
5. Set the Organization Name and Organization Identifier to anything of your liking.
6. Choose Swift as the Language of your project.
7. Finalize the options by pressing the Next button.

projectoptions

8. Choose a location for your project. Xcode will now create everything you need. Have a look in the Project Navigator and find your new iOS application project.
projectnavigator

Step 2.2: Add the dependencies

We will use the popular dependency manager called CocoaPods in our project. This is a great way for us to bring the Microsoft SDK for iOS and its own dependencies into the project.

Before continuing, make sure that you have CocoaPods installed. You can read more about CocoaPods at: https://cocoapods.org/

A simple way of installing CocoaPods is to run the following command in the terminal (using the default Ruby install):

1. Ctrl + Click on your project MSGraph.MailClient and choose New File…

newprojectfile

2. In Other, select Empty and click on the Next button.

newemptyfile

3. Name the file “Podfile” and leave the rest as it is. Click on the Create button to create the empty file.

newpodfile

4. Locate the Podfile in the Project Navigator and open it. Add the following lines to the Podfile.

5. Save the Podfile and close Xcode.
6. Open the Terminal and navigate to the folder containing the Podfile (if you run the command ls you should be able to see the Podfile).
7. Enter and run the following command in the Terminal. This will read the Podfile and install the dependencies.

8. If you follow the output, you should be able to see the Microsoft Graph SDK for iOS being installed (along with its own dependencies).

terminal

9. Now let’s reopen the project. Instead of opening the project with the MSGraph.MailClient.xcodeproj file, we should now use the MSGraph.MailClient.xcworkspace file. You can use the following command in the Terminal.

Step 2.3: Create the bridging header

The Microsoft Graph SDK for iOS is an Objective-C library. Swift and Objective-C can co-exist very well together, but we need to expose the Objective-C library using a bridging header.

1. Ctrl + Click on the project folder MSGraph.MailClient and choose New File…

newappfile

2. In Source, select Header File and click on the Next button.

newheaderfile

3. Name the file MSGraph.MailClient-Bridging-Header and leave the rest as it is. Click on the Create button to create the bridging header file.

bridgingheader

4. In MSGraph.MailClient-Bridging-Header.h, replace the contents of the file with the following snippet. This will expose the Microsoft Graph SDK for iOS to be used with Swift.

5. Save the MSGraph.MailClient-Bridging-Header.h file.

The last piece is to make sure that the project knows about the bridging file. We can do so in the project settings.

1. Select the top item in the Project Navigator (“MSGraph.MailClient-Bridging-Header”), this will display the project settings.

selecttop
2. Click on Build Settings and search for “Bridging Header”.

buildsettings2

3. Double-click at the area for the value of the Objective-C Bridging Header setting. This will show a larger text field.
4. Drag the MSGraph.MailClient-Bridging-Header.h file onto this area. This will enter the path for the bridging file, needed by the compiler.

addheadertosettings
5. Build the project using the ⌘B shortcut, or by pressing the Build button in the Product menu.

Step 3.1: Add the MailClient class

Now let’s create the class that is going to use the Microsoft Graph SDK for iOS. This class will take care of signing in the user, getting the user profile and finally send the mail with a message.

1. Ctrl + Click on the project folder MSGraph.MailClient and choose New File…

newappfile

2. In Source, select Swift File and click on the Next button.

newswiftfile

3. Name the file MailClient and leave the rest as it is. Click on the Create button to create the Swift file.

mailclientname

4. In MailClient.swift, add the following struct below the import statement. This struct will contain a few constant values that we will use in the class.

5. In MailClient.swift, add the following class base below the MailClientConstants struct.

6. Inside the MailClient class, add the following three variables.

ADALDependencyResolver: The authentication resolver used by the Microsoft Graph SDK for iOS. This object comes from ADAL (Active Directory Authentication Library) and will be using the configuration that you created earlier in this post using Azure AD. We will copy the configuration from Azure AD into a property list file.
MSGraphServiceClient: This is the Microsoft Graph client from the Microsoft Graph SDK for iOS. This client allows us to perform operations towards the Microsoft Graph using an object model.
Ready: This variable will signal if a user has been signed in and the MailClient is ready to be used.

7. Your MailClient.swift file should now look like this:

Step 3.2: Add the initializer

Inside the MailClient class, add the following initialization function below the three variables. This function will initialize the three variables whenever an object of type MailClient is instantiated.

Step 3.3: Add the getGraphServiceUrl function

Inside the MailClient class (MailClient.swift), add the following function below init function. This function will combine the Microsoft Graph endpoint URL and the version parameter.

Step 3.4: Add the signInWithCallback function

Inside the MailClient class (MailClient.swift), add the following function below the getGraphServiceUrl function. This function requests ADAL to trigger an interactive logon session (with UI). Depending on the result of the session, the MailClient may or may not be put in a ready state.

Step 3.5: Add the getUserWithCallback function

Inside the MailClient class (MailClient.swift), add the following function below the signInWithCallback function. This function uses the Microsoft Graph client to read the signed in user profile. This is how we will extract the mail address of the signed in user.

Step 3.6: Add the createRecipientWithAddress function

Inside the MailClient class (MailClient.swift), add the following function below the getUserWithCallback function. This function creates a recipient object that we can use when engaging with the Microsoft Graph.

Step 3.7: Add the createBodyWithContent function

Inside the MailClient class (MailClient.swift), add the following function below the createRecipientWithAddress function. This function creates a body object that we can use when engaging with the Microsoft Graph. We will default to creating an HTML body.

Step 3.8: Add the createMessageWithSubject function

Inside the MailClient class (MailClient.swift), add the following function below the createBodyWithCallback function. This function creates a message object that we can use when engaging with the Microsoft Graph. It uses the createRecipientWithAddress function and createBodyWithContent function to build the completed message object.

Step 3.9: Add the sendMailWithMessage function

Inside the MailClient class (MailClient.swift), add the following function below the createMessageWithSubject function. This function takes a completed message object and sends it (on behalf of the signed in user) using the Microsoft Graph client.

Step 3.10: Add the sendMeWithCallback function

Inside the MailClient class (MailClient.swift), add the following function below the sendMailWithMessage function. This function aggregates the above logic to create the following flow:

  1. Let a user sign in.
  2. Get the user profile (mail address).
  3. Create the message.
  4. Send the message to the current user (on behalf of the current user).

In addition, we pass a logging mechanism to the function. This way we can let those status messages surface to the application interface, and follow the different steps as they execute.

Your MailClient.swift file should now look like this: https://github.com/simonjaeger/PnP/blob/msgraph-ios-samples/Samples/MicrosoftGraph.iOS.Swift.SendMail/MSGraph.MailClient/MailClient.swift

Build the project using the ⌘B shortcut, or by pressing the Build button in the Product menu.

Step 3.11: Configure ADAL with your Azure AD application

We need to get back into our Azure AD application configuration page to extract a few properties and put them into the project. The ADALDependencyResolver will try to initialize with a Property List file names adal_settings.plist – so we need to create that.

1. Ctrl + Click on the project folder MSGraph.MailClient and choose New File…

newappfile

2. In Resource, select Property List and click on the Next button.

newplist

3. Name the file “adal_settings” and leave the rest as it is. Click on the Create button to create the property list file.

adal_settings

4. Head back into the current Azure portal (https://manage.windowsazure.com/), to the configuration page of your Azure AD application.
5. Locate the Client ID property and the Redirect URIs property.

appsettings

6. In adal_settings.plist, add the following String items (rows) to the Root item.

ClientId: The ClientId of your Azure AD application.
ResourceId: The resource identifier of the Microsoft Graph, which is “https://graph.microsoft.com/”.
RedirectUri: One of the Redirect URIs listed in your Azure AD application, which is “https://MicrosoftGraph.iOS.Swift.SendMail/”.
AuthorityUrl: This is “https://login.microsoftonline.com/” combined with the name of your Azure AD tenant. In example, this would be “https://login.microsoftonline.com/contoso.onmicrosoft.com/” for the Azure AD tenant “contoso.onmicrosoft.com”.

adal_settings2

7. Save your work using the ⌘S shortcut.

Step 4.1: Update the UI

In order to test everything, let’s hook up some UI. This is not going to be specific to the Microsoft Graph SDK for iOS. So I will only cover this briefly. You can learn more about UIKit at: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKit_Framework/

1. In ViewController.swift, add the following variables at the top of the class. The @IBOutlet variables will be references to a few UI elements that we will add to the Storyboard.

2. In ViewController.swift, add the following functions inside the class. This is the logging function and event handler for when a button is pressed. When the button is pressed we will trigger the MailClient go through the steps for sending ourselves a mail.

3. Your ViewController.swift file should now look like this (apart from some styling specifics): https://github.com/simonjaeger/PnP/blob/msgraph-ios-samples/Samples/MicrosoftGraph.iOS.Swift.SendMail/MSGraph.MailClient/ViewController.swift

4. In Main.storyboard, use the Object Library to drag three items onto the View Controller surface. A Label, a Button and an Activity Indicator View.

uiitems

5. [OPTIONAL] In Main.storyboard, layout and style everything as you please. You can learn more about Storyboards here: https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/Storyboard.html
6. Connect the Storyboard outlets and actions to the @IBOutlet variables and the @IBAction function in the ViewController. In Main.storyboard, Ctrl + Click on the View Controller item in the View Controller Scene. This will show a list of the @IBOutlet variables and the @IBActions functions in the View Controller.

  1. Drag from “button” to the button in the Storyboard.
  2. Drag from “label” to the button in the Storyboard.
  3. Drag from “spinner” to the activity indicator view in the Storyboard.
  4. Drag from “sendMe:” to the button in the Storyboard, choose Touch Up Inside in order to trigger the sendMe function inside the View Controller when the button is tapped.

storyboard

Now – run the project using the ⌘R shortcut, or by pressing the Run button in the Product menu.

This should generate a mail in the iOS application and send it to yourself. At this point, go ahead and check your mailbox!

app

Wrap up

View the source code files included in this blog post (https://github.com/simonjaeger/PnP/tree/msgraph-ios-samples/Samples/MicrosoftGraph.iOS.Swift.SendMail) for a final reference of how your code should be structured (if needed). You should now have grasped an understanding of a few possibilities of interacting (and authenticating) with the Microsoft Graph.

-Simon Jaeger