SharePoint Integration with iOS Application: Contacts

Hello again! Continuing with my previous post SharePoint Integration with iOS Application, now that we are through with the login and authentication of user, let’s start with performing CRUD operations on SharePoint Contacts.

Here’s a sample project on this: office365Demo. You’re welcome! 🙂

For now, will detail on how to get started with code snippets that you can use in your project.

I have also created a set of helper classes which you can directly add to your project and to make use of the utility methods MSOHelper.

Getting Auth Token and creating OAuthentication object:

Import the below two classes that are required for server interaction.

#import <office365-lists-sdk/OAuthentication.h>
#import <office365-lists-sdk/HttpConnection.h>

Get the Auth token after successful authentication from the below method as described here.

- (void)authentcateUserWithAuthority:(NSString *)iAuthority resourceID:(NSString *)iResourceID redirectURI:(NSString *)iRedirectURI andClientID:(NSString *)iClientID;

Create a property in the class to hold an OAuthentication instance required for creating connections.

@property (nonatomic, strong) OAuthentication *authCredentials;

Add the line self.authCredentials = [[OAuthentication alloc] initWith:result.accessToken]; to the method as below if the auth is successful.

	// handle authentication error or success with
	// result.error or result.accessToken ...
	if (result.error) {
		NSLog(@"Error getting token: %@", result.error.localizedDescription);
		[[[UIAlertView alloc] initWithTitle:@"Error" message:result.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
	} else {
		NSLog(@"Authenticaton Successful!");
		self.authCredentials = [[OAuthentication alloc] initWith:result.accessToken];
		[[[UIAlertView alloc] initWithTitle:@"Success" message:@"Login Successful" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
	}


Performing CRUD operations on Contacts:

For performing CRUD operations, you can use the helper class MSOContactHelper by importing the MSOContactHelper.h and MSOCOntactHelper.m files to your project from here. You might have to do cleanup in the classes as per your requirements.

If you’re unsure, read on.

You have already defined the Resource ID as below if you have followed the previous blog. (myTenant below is just a placeholder. Replace it with your tenant name)

#define ResourceID @"https://myTenant.sharepoint.com"

Below are the methods I have created to perform various operations on the contacts. Add the below methods to your project and call the respective methods when necessary. Also, you will have to send the correct Contact ID for update/delete operations.

#pragma mark - Contact Operation Methods

- (void)getContacts {
    NSString *url = [NSString stringWithFormat:@"%@/sites/portal/_api/lists/GetByTitle('%@')/Items", ResourceID, [@"Contacts" urlencode]];
    HttpConnection *connection = [[HttpConnection alloc] initWithCredentials:self.authCredentials url:url];
    
    [[connection execute:@"GET" callback:^(NSData *data, NSURLResponse *response, NSError *error) {
        [self handleResponse:data withResponse:response andError:error];
    }] resume];
}

- (void)createContact:(NSData *)data {
    NSString *url = [NSString stringWithFormat:@"%@/sites/portal/_api/lists/GetByTitle('%@')/Items", ResourceID, [@"Contacts" urlencode]];
    HttpConnection *connection = [[HttpConnection alloc] initWithCredentials:self.authCredentials url:url bodyArray:data];
    
    [[connection execute:@"POST" callback:^(NSData *data, NSURLResponse *response, NSError *error) {
        [self handleResponse:data withResponse:response andError:error];
    }] resume];
}

- (void)updateContactID:(NSUInteger)contactID withData:(NSData *)data {
    NSString *url = [NSString stringWithFormat:@"%@/sites/portal/_api/lists/GetByTitle('%@')/Items(%ld)", ResourceID, [@"Contacts" urlencode], contactID];
    HttpConnection *connection = [[HttpConnection alloc] initWithCredentials:self.authCredentials url:url bodyArray:data];
    
    [[connection execute:@"MERGE" callback:^(NSData *data, NSURLResponse *response, NSError *error) {
        [self handleResponse:data withResponse:response andError:error];
    }] resume];
}

- (void)deleteContactID:(NSUInteger)contactID {
    NSString *url = [NSString stringWithFormat:@"%@/sites/portal/_api/lists/GetByTitle('%@')/Items(%ld)", ResourceID, [@"Contacts" urlencode], contactID];
    HttpConnection *connection = [[HttpConnection alloc] initWithCredentials:self.authCredentials url:url];
    
    [[connection execute:@"DELETE" callback:^(NSData *data, NSURLResponse *response, NSError *error) {
        [self handleResponse:data withResponse:response andError:error];
    }] resume];
}

- (NSArray *)handleResponse:(NSData *)data withResponse:(NSURLResponse *)response andError:(NSError *)error {
    NSLog(@"Data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    NSLog(@"Response: %@", response);
    if (error) NSLog(@"Error: %@", error);
    
    NSLog(@"\nParsed Response Data");
    NSMutableArray *array = [NSMutableArray array];
    
    NSMutableArray *listsItemsArray = [self parseDataArray: data];
    for (NSDictionary* value in listsItemsArray) {
        [array addObject: value];
    }
    NSLog(@"Array: %@", array);
    
    return array;
}

#pragma mark - Utility methods

- (NSMutableArray *)parseDataArray:(NSData *)iData {
    NSMutableArray *array = [NSMutableArray array];
    NSError *error;
    NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:[self sanitizeJson:iData]
                                                               options:NSJSONReadingMutableContainers
                                                                 error:&error];
    NSArray *jsonArray = [[jsonResult valueForKey:@"d"] valueForKey:@"results"];
    
    if (jsonArray != nil) {
        for (NSDictionary *value in jsonArray) {
            [array addObject:value];
        }
    } else {
        NSDictionary *jsonItem = [jsonResult valueForKey:@"d"];
        
        if (jsonItem != nil) {
            [array addObject:jsonItem];
        }
    }
    
    return array;
}

- (NSData *)sanitizeJson:(NSData *)iData {
    NSString *dataString= [[NSString alloc] initWithData:iData encoding:NSUTF8StringEncoding];
    NSString *replacedDataString = [dataString stringByReplacingOccurrencesOfString:@"E+308" withString:@"E+127"];
    NSData *bytes = [replacedDataString dataUsingEncoding:NSUTF8StringEncoding];
    
    return bytes;
}


Sample JSON Format for Create/Update contact:

Below is the sample format required for creating/updating a contact.

{
    "Title": "myLastName",
    "FirstName": "myFirstName",
    "FullName": "myFullName",
    "Email": "vijay@myCompany.com",
    "Company": "my Company",
    "JobTitle": "my Job",
    "WorkPhone": "018301411415",
    "HomePhone": "134356787655",
    "CellPhone": "907585213235",
    "WorkFax": "987654434565",
    "WorkAddress": "my Address",
    "WorkCity": "my City",
    "WorkState": "my State",
    "WorkZip": "1234567",
    "WorkCountry": "my Country",
    "Comments": "my Comments",
    "WebPage": {
        "Description": "myCompDescription",
        "Url": "http://www.myCompanyWebsite.com"
    }
}

Tip: Save this as a .json file, say 'contactDetails.json' and add it to the project.

Now you can call the createContact/updateContact methods as below to check if everything is fine. (Make sure to set the correct contact ID for update; Am using 1 below).

// Get the data from JSON
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"contactDetails" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
// Create Contact
[self createContact:data];
// Updating Contact
[self updateContactID:1 withData:data];

That’s it! Are you wishing if someone had built a UI around this for you as well? 😛

So far, we are only printing the logs here after performing any operation on the contacts.

For a working code with UI and all the operations head to: office365Demo

Thanks for visiting!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s