Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

Outlook Contacts: List Contact Folders and Child Folders

See more Outlook Contact Examples

Enumerate the contactFolders collection, then each discovered folder's childFolders. A queue handles nested folders and nextLink pagination at every level. IDs and parentFolderId remain strings, so applications can reconstruct the hierarchy. Duplicate folder IDs are not traversed twice. This lists folders, not their contacts; use the existing contact-list example with a chosen folder ID.

The default Contacts folder's own contacts are read through /me/contacts. To obtain their folder ID for folder-scoped operations, read parentFolderId from a contact in that folder. Names are neither unique nor reliable identifiers across languages. This demonstration stops at 100 total HTTP requests and reports incomplete traversal; production code should persist the queue/position and processed-ID set when resuming.

Delegated permission: Contacts.Read.

Uses Microsoft Graph v1.0 for contacts stored in an Outlook.com or Microsoft 365 mailbox. These are personal mailbox contacts, not Microsoft Entra directory users, organizational contacts (/contacts), or the People API. Obtain a delegated token with the contacts OAuth2 example; the cache is qa_data/tokens/outlookContacts.json. A token for Calendar, SMTP, or another resource without the needed Graph contacts permission is insufficient.

/me requires a signed-in user. An authorized unattended Microsoft 365 application instead needs application permissions and administrator consent, and targets /users/{id-or-UPN}. App-only access does not apply to personal Outlook.com mailboxes. Shared folders require actual sharing rights and Contacts.Read.Shared or Contacts.ReadWrite.Shared delegated consent. The examples target the global cloud.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and contact data private.

Microsoft documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoStringTable.h>
#import <CkoHashtable.h>
#import <CkoStringBuilder.h>
#import <NSString.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
//  Obtain a delegated Microsoft Graph token using the contacts authorization example.
//  See Authorize Outlook Contacts with OAuth2 and PKCE.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/outlookContacts.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not read the private contacts token cache.");
    return;
}

if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.AuthToken = [token StringOf: @"access_token"];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:30];
[http SetRequestHeader: @"Accept" value: @"application/json"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoStringTable *pending = [[CkoStringTable alloc] init];
CkoHashtable *seenLinks = [[CkoHashtable alloc] init];
CkoHashtable *seenFolders = [[CkoHashtable alloc] init];
[pending Append: @"https://graph.microsoft.com/v1.0/me/contactFolders?$select=id,displayName,parentFolderId&$top=50"];
CkoStringBuilder *link = [[CkoStringBuilder alloc] init];
CkoStringBuilder *childrenUrl = [[CkoStringBuilder alloc] init];
int position = 0;
while (((position < [pending.Count intValue]) && (position < 100))) {
    NSString *url = [pending StringAt: [NSNumber numberWithInt: position]];
    [link Clear];
    [link Append: url];
    if ([link StartsWith: @"https://graph.microsoft.com/v1.0/" caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Unexpected folder-list host; no request sent.");
        return;
    }

    if ([seenLinks Contains: url] == YES) {
        NSLog(@"%@",@"Repeated continuation; cannot establish completeness.");
        return;
    }

    [seenLinks AddInt: url value: [NSNumber numberWithInt: 1]];
    success = [http HttpNoBody: @"GET" url: url response: resp];
    //  A false result can still include an HTTP error response.
    if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
        NSLog(@"%@",@"No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
        return;
    }

    if ([resp.StatusCode intValue] != 200) {
        NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
        NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
        if ([resp.StatusCode intValue] == 429) {
            NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
        }

        if ([resp.StatusCode intValue] == 401) {
            NSLog(@"%@",@"Refresh the Graph access token or authorize again.");
        }

        return;
    }

    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a well-formed JSON response.");
        return;
    }

    if ([[result JsonTypeOf: @"value"] intValue] != 4) {
        NSLog(@"%@",@"Expected a folder array.");
        return;
    }

    int i = 0;
    while ((i < [[result SizeOfArray: @"value"] intValue])) {
        result.I = [NSNumber numberWithInt: i];
        if (([[result JsonTypeOf: @"value[i].id"] intValue] != 1) || ([result StringOfEquals: @"value[i].id" value: @"" caseSensitive: YES] == YES)) {
            NSLog(@"%@",@"Expected a nonempty value[i].id in the JSON.");
            return;
        }

        NSString *folderId = [result StringOf: @"value[i].id"];
        if ([seenFolders Contains: folderId] == NO) {
            [seenFolders AddInt: folderId value: [NSNumber numberWithInt: 1]];
            NSLog(@"%@%@",@"Folder ID: ",folderId);
            NSLog(@"%@%@",@"Name: ",[result StringOf: @"value[i].displayName"]);
            NSLog(@"%@%@",@"Parent ID: ",[result StringOf: @"value[i].parentFolderId"]);
            [childrenUrl Clear];
            [childrenUrl Append: @"https://graph.microsoft.com/v1.0/me/contactFolders/"];
            [childrenUrl Append: [http UrlEncode: folderId]];
            [childrenUrl Append: @"/childFolders?$select=id,displayName,parentFolderId&$top=50"];
            [pending Append: [childrenUrl GetAsString]];
        }

        i = i + 1;
    }

    int nextType = [[result JsonTypeOf: @"\"@odata.nextLink\""] intValue];
    if ((nextType != -1) && (nextType != 6)) {
        if (([[result JsonTypeOf: @"\"@odata.nextLink\""] intValue] != 1) || ([result StringOfEquals: @"\"@odata.nextLink\"" value: @"" caseSensitive: YES] == YES)) {
            NSLog(@"%@",@"Expected a nonempty \"@odata.nextLink\" in the JSON.");
            return;
        }

        [pending Append: [result StringOf: @"\"@odata.nextLink\""]];
    }

    position = position + 1;
}

if (position < [pending.Count intValue]) {
    NSLog(@"%@",@"Stopped at 100 HTTP requests. Save the pending queue and current position privately to resume.");
    return;
}

NSLog(@"%@%d",@"Folder traversal complete. Folders: ",[seenFolders.Count intValue]);