Export (0) Print
Expand All

Tutorial: create an iOS OneNote API app

Last modified: November 13, 2014

Applies to: OneNote service

In this article
Create a "hello world" IPhone OneNote app
Build and run the app
Additional resources

Use this tutorial to create a simple "hello world" IPhone app that uses the Microsoft OneNote API to save HTML documents to a Microsoft OneNote notebook.

You can also download a complete OneNote API IOS sample from GitHub.

If you are just getting started with IPhone and iOS development, visit the Apple developer site for more information about getting a developer account and iOS development in general. If you are an experienced iOS developer you’ll probably already have some of the resources listed below, but you’ll need to be sure that you have the Live SDK for iOS.

Here’s what you’ll need to use this tutorial:

  • Xcode5 download provides direct access to download the Apple development environment. You can also download the XCode tools from the Mac App Store.

  • Live SDK for iOS is hosted on GitHub. We recommend you use this library in all iOS store apps that use the OneNote API.

  • Live SDK for iOS help gives you information about downloading and using the SDK.

Your users will need to have Microsoft accounts, and you will need to get a client ID for your app. For more information about how to get a Microsoft account and a client ID for your app, see Get a client ID for use with the OneNote service API.

The OneNote API requires dates with ISO 8601 formatting, so your real-world apps will also need to include the ISO 8601 date formatter library. You can look at the fuller OneNote IOS sample to learn how to work with this library. You’ll have to turn off automatic reference counting for this one library when you build a project that uses it. You do that by adding the following compiler flag to the ISO8601DateFormatter.m file.

-fno obj -arc

The fuller sample also uses the AFNetworking framework.

To create and set up the project

  1. Start XCode, if it is not already running.

  2. Choose File>New and select Project.

  3. In the Choose a template for your project window, select Single View Application. Choose the Next button.

  4. In the Choose options for your new project window, add OneNoteServiceIPhoneHelloWorld to the Product Name text box. Accept all of the other defaults and choose the Next button.

  5. Choose the Create button.

NoteNote

If you are new to iOS development, you can follow the tutorial in Start Developing iOS Apps Today to get introduced to creating iOS apps.

After you have created the project, import the Live SDK for iOS.

To import the Live SDK source code

  1. Download the Live SDK for iOS.

  2. Extract the LiveSDK.framework.zip file from the bin folder of the SDK.

  3. Open your project in Xcode.

  4. In the Project Navigator, select your project. Select your build target, and then select the Build Phases tab.

  5. Expand the Link Binary With Libraries section, and then choose the + button to add an item.

  6. Choose the Add Other… button. Browse to and select the LiveSDK.framework folder that you downloaded and extracted earlier. Choose the Open button.

  7. In the Project Navigator on the left, drag the LiveSDK.framework node from the Frameworks folder and drop it into the Copy Bundle Resources section of the Build Phases tab in the project target editor.

Figure 1 shows how the contents of your package explorer will look in XCode.

Figure 1. Contents of the package explorer in XCode

OneNote app in the XCode project explorer

Now you are ready to create the basic resources and files for your app.

Edit the storyboard for your app

In the project navigator, select the Main_iPhone.storyboard file. Create two buttons. Label one button Login and the other Create Page. Select View > Utilities > Show Object Library if you don’t see the Object library.

Figure 2 shows how the single view should look in the storyboard.

NoteNote

For more information about how to create storyboards and integrate them into your apps, see Tutorial: Storyboards.

Figure 2. Design of the single view in the storyboard

OneNote IPhone app detail view controller

Now you are ready to connect the two buttons to IBAction methods in the ViewController.m file.

To create the action methods

  1. Open the Main_iPhone.Storyboard file.

  2. Choose the Assistant editor button (The assistant editor button looks like a bow tie.) at the top right of the editor. This allows you to open the ViewController.m file in a second window to the right of the Main_iPhone.Storyboard file.

  3. Right-click the Login button, select Touch Up Inside, and drag the button to the ViewController.m file on the right. Name the action Login.

  4. Right-click the Create Page button, select Touch Up Inside, and drag the button to the ViewController.m file on the right. Name the action CreatePage. You will see the following two methods in the ViewController.m file.

    - (IBAction)Login:(id)sender {
    
    }
    - (IBAction)CreatePage:(id)sender {
    
    }
    
    

Now you can write the code that will run the app.

Add code to ViewController.h and ViewController.m

Update the ViewController.h file so that it includes LiveSdk/LiveConnectClient.h. Also update the interface declaration so that it contains protocol declarations for LiveAuthDelegate, NSURLConnectionDelegate, and NSURLConnectionDataDelegate. The following code shows how the updated ViewController.h file will look.

#import <UIKit/UIKit.h>
#import <LiveSdk/LiveConnectClient.h>

@interface ViewController : UIViewController <LiveAuthDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@end

Add the following code to the Login method in the ViewController.m file. This code logs the action and kicks off the authentication process for your users. You’ll see a build error after you paste this code, but it will disappear after you complete the app.


- (IBAction)Login:(id)sender {
    NSLog(@"Login");
    [self authenticate:self];
}

Add the following code to the CreatePage method in the ViewController.m file. This code creates a simple HTML page and passes it to the OneNote API. It also logs the action. The request metadata includes a hard-coded date with ISO 8601 formatting.


- (IBAction)CreatePage:(id)sender {
    NSLog(@"Create page");
    
    NSString *simpleHtml = @"<html>"
    "<head>"
    "<title>A simple page created from basic HTML-formatted text from iOS</title>"
    "<meta name=\"created\" content=\"2013-05-22T14:24Z\" />"
    "</head>"
    "<body>"
    "<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>"
    "</body>"
    "</html>";
    
    NSData *presentation = [simpleHtml dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:PagesEndPoint]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = presentation;
    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    
    if (liveClient.session)
    {
        [request setValue:[@"Bearer " stringByAppendingString:liveClient.session.accessToken] forHTTPHeaderField:@"Authorization"];
    }
    
    // Send the HTTP request
    currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
}

The rest of the code handles the authentication steps, processes the contents of the response from the OneNote API, and logs the results of the authentication and page creation requests. The following code shows how ViewController.m will look once you have added all of this code, including the contents of the Login and CreatePage methods.

Use the client ID that you got when you registered your app as the value of the ClientId constant.

#import "ViewController.h"

@interface ViewController ()
{
    // Main Live API object
    LiveConnectClient *liveClient;
    
    // The in-progress connection
    NSURLConnection *currentConnection;
    
    // Response from the current in-progress request
    NSHTTPURLResponse *returnResponse;
    
    // Data being built for the current in-progress request
    NSMutableData *returnData;
}
@end

@implementation ViewController

// The endpoint for the OneNote service
NSString *const PagesEndPoint = @"https://www.onenote.com/api/v1.0/pages";

// Add the client ID for your application from the Live application management page.
// Example: 0000000012345678
static NSString *const ClientId = @"  ";

// Scopes to request permissions for from Live
static NSString *ScopeStrings = @"wl.signin wl.basic Office.OneNote_Create";

// Executes once, when the view initially loads
- (void)viewDidLoad
{
    // Tokenize the scopes
    NSArray *scopes = [ScopeStrings componentsSeparatedByString:@" "];
    
    // Initialize the Live SDK client
    liveClient = [[LiveConnectClient alloc] initWithClientId:ClientId
                                                      scopes:scopes
                                                    delegate:self
                                                   userState:@"init"];
    
    [super viewDidLoad];
}

// This method is called when clicking on the "Login" button
- (IBAction)Login:(id)sender {
    NSLog(@"Login");
    [self authenticate:self];
}

// This method is called when clicking on the "Create page" button
- (IBAction)CreatePage:(id)sender {
    NSLog(@"Create page");
    
    NSString *simpleHtml = @"<html>"
    "<head>"
    "<title>A simple page created from basic HTML-formatted text from iOS</title>"
    "<meta name=\"created\" content=\"2013-05-22T14:24Z\" />"
    "</head>"
    "<body>"
    "<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>"
    "</body>"
    "</html>";
    
    NSData *presentation = [simpleHtml dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:PagesEndPoint]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = presentation;
    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    
    if (liveClient.session)
    {
        [request setValue:[@"Bearer " stringByAppendingString:liveClient.session.accessToken] forHTTPHeaderField:@"Authorization"];
    }
    
    // Send the HTTP request
    currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
}

// When body data arrives, store it
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [returnData appendData:data];
}

// When a response starts to arrive, allocate a data buffer for the body
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    returnData = [[NSMutableData alloc] init];
    returnResponse = (NSHTTPURLResponse *)response;
}

// Handle parsing the response from a finished service call
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    int status = [returnResponse statusCode];
    if (status == 201)
    {
        NSLog(@"Page created!");
    }
    else
    {
        NSLog(@"There was an error creating the page. Response code: %d", status);
    }
}

// Pop out the Live SDK UI
- (void)authenticate:(UIViewController *)controller {
    assert(liveClient);
    assert(controller);
    
    if (!liveClient.session) {
        NSLog(@"Logging in");
        [liveClient login:controller delegate:nil userState:@"login"];
    }
    else {
        NSLog(@"Logging out");
        [liveClient logoutWithDelegate:self userState:@"logout"];
    }
}

@end

Once you have finished setting up and writing the app, you can test it by running it from XCode in an IPhone emulator. Use the Login button to sign in with your Microsoft account, and then use the Create Page create a simple HTML page. The output window in XCode will display the log messages that you added to the Login, CreatePage, connectionDidFinishLoading, and authenticate methods.

Show:
© 2014 Microsoft