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

Outlook Contacts: Synchronize Contacts in a Folder with Delta Queries

See more Outlook Contact Examples

Build a local contact projection for one folder, then retrieve incremental changes on later runs. Supply a folder ID from folder enumeration or a contact's parentFolderId. This uses /me/contactFolders/{id}/contacts/delta, not a calendar-style date window. The initial $select requests id, displayName, emailAddresses, and mobilePhone. The saved projection is not a full contact archive.

Follow exact nextLink URLs within a round; save the final deltaLink for the next round. Do not rebuild opaque tokens or re-add query options. Preserve the same ID preference and field selection. Contact IDs remain strings; their hashes are only JSON-safe local keys. @removed records are tombstones (removed=true) to exclude from this local folder view. A removal can reflect a move out of the folder, not necessarily a global deletion. Repeated changes update the same record; omitted fields are retained, explicit nulls clear scalar values, and present email arrays replace the saved array.

The checkpoint stores contact data and the continuation URL together, with a backup of the previous matching pair before replacement. HTTP/validation failures do not advance it. If the main file is damaged, recover the private .bak pair. Replaying a page is safe for these upserts and tombstones. Production storage should atomically commit data and cursor. Use one writer and a separate cache for each account/folder/projection. The sample rejects a different folder ID and pauses after 100 pages with its nextLink saved. A rejected or expired sync state requires a new baseline and deliberate reconciliation of the old view.

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 <NSString.h>
#import <CkoFileAccess.h>
#import <CkoStringBuilder.h>
#import <CkoCrypt2.h>
#import <CkoHashtable.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;
[http SetRequestHeader: @"Prefer" value: @"IdType=\"ImmutableId\", odata.maxpagesize=50"];
NSString *folderId = @"YOUR_CONTACT_FOLDER_ID";
CkoFileAccess *fac = [[CkoFileAccess alloc] init];
success = [fac DirEnsureExists: @"qa_data/outlookContacts"];
if (success != YES) {
    NSLog(@"%@",@"Could not create the private synchronization directory.");
    return;
}

NSString *cachePath = @"qa_data/outlookContacts/contacts-sync.json";
NSString *backupPath = @"qa_data/outlookContacts/contacts-sync.json.bak";
CkoJsonObject *state = [[CkoJsonObject alloc] init];
state.Strict = YES;
if ([fac FileExists: cachePath] == YES) {
    success = [state LoadFile: cachePath];
    if (success != YES) {
        NSLog(@"%@",@"Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.");
        return;
    }

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

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

    if ([state StringOfEquals: @"folderId" value: folderId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"This checkpoint belongs to another folder. Use a separate cache.");
        return;
    }

    if ([[state JsonTypeOf: @"items"] intValue] != 3) {
        NSLog(@"%@",@"Expected an items object in the checkpoint.");
        return;
    }

}
else {
    CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
    [endpoint Append: @"https://graph.microsoft.com/v1.0/me/contactFolders/"];
    [endpoint Append: [http UrlEncode: folderId]];
    [endpoint Append: @"/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone"];
    [state UpdateString: @"folderId" value: folderId];
    [state UpdateString: @"resumeUrl" value: [endpoint GetAsString]];
    [state UpdateNewObject: @"items"];
}

CkoCrypt2 *hash = [[CkoCrypt2 alloc] init];
hash.HashAlgorithm = @"sha256";
hash.Charset = @"utf-8";
hash.EncodingMode = @"hex";
CkoStringBuilder *link = [[CkoStringBuilder alloc] init];
CkoStringBuilder *itemPath = [[CkoStringBuilder alloc] init];
CkoHashtable *seenLinks = [[CkoHashtable alloc] init];
CkoJsonObject *previous = [[CkoJsonObject alloc] init];
previous.Strict = YES;
int pageCount = 0;
while ((pageCount < 100)) {
    NSString *url = [state StringOf: @"resumeUrl"];
    [link Clear];
    [link Append: url];
    if ([link StartsWith: @"https://graph.microsoft.com/v1.0/" caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Unexpected continuation host or API version; no request sent.");
        return;
    }

    if ([seenLinks Contains: url] == YES) {
        NSLog(@"%@",@"Repeated continuation URL; stopping.");
        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 value array; checkpoint unchanged.");
        return;
    }

    //  Exactly one continuation member must be a nonempty string.
    int nextType = [[result JsonTypeOf: @"\"@odata.nextLink\""] intValue];
    int deltaType = [[result JsonTypeOf: @"\"@odata.deltaLink\""] intValue];
    BOOL finished = NO;
    NSString *resumeUrl = 0;
    if ((nextType == 1) && (deltaType == -1)) {
        resumeUrl = [result StringOf: @"\"@odata.nextLink\""];
    }
    else {
        if ((deltaType != 1) || (nextType != -1)) {
            NSLog(@"%@",@"Invalid delta continuation; checkpoint unchanged.");
            return;
        }

        resumeUrl = [result StringOf: @"\"@odata.deltaLink\""];
        finished = YES;
    }

    [link Clear];
    [link Append: resumeUrl];
    if ([link StartsWith: @"https://graph.microsoft.com/v1.0/" caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Invalid continuation URL; checkpoint unchanged.");
        return;
    }

    success = [previous Load: [state Emit]];
    if (success != YES) {
        NSLog(@"%@",@"Could not snapshot the previous checkpoint.");
        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 *contactId = [result StringOf: @"value[i].id"];
        NSString *itemKey = [hash HashStringENC: contactId];
        if (hash.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not form a local record key.");
            return;
        }

        //  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        [itemPath Clear];
        [itemPath Append: @"items."];
        [itemPath Append: itemKey];
        if ([[state JsonTypeOf: [itemPath GetAsString]] intValue] != 3) {
            [state UpdateNewObject: [itemPath GetAsString]];
        }

        [itemPath Append: @"."];
        state.PathPrefix = [itemPath GetAsString];
        [state UpdateString: @"id" value: contactId];
        if ([[result JsonTypeOf: @"value[i].@removed"] intValue] == 3) {
            //  Hide records with removed=true from the local folder view.
            [state UpdateBool: @"removed" value: YES];
            NSLog(@"%@%@",@"Removed from the local view: ",contactId);
        }
        else {
            [state UpdateBool: @"removed" value: NO];
            int displayNameType = [[result JsonTypeOf: @"value[i].displayName"] intValue];
            if (displayNameType == 1) {
                [state UpdateString: @"displayName" value: [result StringOf: @"value[i].displayName"]];
            }
            else {
                if (displayNameType == 6) {
                    [state UpdateNull: @"displayName"];
                }
                else {
                    if (displayNameType != -1) {
                        NSLog(@"%@",@"Invalid contact field; checkpoint unchanged.");
                        return;
                    }

                }

            }

            int mobilePhoneType = [[result JsonTypeOf: @"value[i].mobilePhone"] intValue];
            if (mobilePhoneType == 1) {
                [state UpdateString: @"mobilePhone" value: [result StringOf: @"value[i].mobilePhone"]];
            }
            else {
                if (mobilePhoneType == 6) {
                    [state UpdateNull: @"mobilePhone"];
                }
                else {
                    if (mobilePhoneType != -1) {
                        NSLog(@"%@",@"Invalid contact field; checkpoint unchanged.");
                        return;
                    }

                }

            }

            int emailType = [[result JsonTypeOf: @"value[i].emailAddresses"] intValue];
            if (emailType == 4) {
                //  Replace this collection when present, including an empty array that clears it.
                [state UpdateNewArray: @"emailAddresses"];
                int j = 0;
                while ((j < [[result SizeOfArray: @"value[i].emailAddresses"] intValue])) {
                    result.J = [NSNumber numberWithInt: j];
                    state.J = [NSNumber numberWithInt: j];
                    if (([[result JsonTypeOf: @"value[i].emailAddresses[j].address"] intValue] != 1) || ([result StringOfEquals: @"value[i].emailAddresses[j].address" value: @"" caseSensitive: YES] == YES)) {
                        NSLog(@"%@",@"Expected a nonempty value[i].emailAddresses[j].address in the JSON.");
                        return;
                    }

                    [state UpdateString: @"emailAddresses[j].address" value: [result StringOf: @"value[i].emailAddresses[j].address"]];
                    if ([[result JsonTypeOf: @"value[i].emailAddresses[j].name"] intValue] == 1) {
                        [state UpdateString: @"emailAddresses[j].name" value: [result StringOf: @"value[i].emailAddresses[j].name"]];
                    }

                    j = j + 1;
                }

            }
            else {
                if (emailType != -1) {
                    NSLog(@"%@",@"Invalid email collection; checkpoint unchanged.");
                    return;
                }

            }

            state.PathPrefix = @"";
            NSLog(@"%@%@",@"Updated local contact: ",contactId);
        }

        state.PathPrefix = @"";
        i = i + 1;
    }

    [state UpdateString: @"resumeUrl" value: resumeUrl];
    [state UpdateBool: @"roundComplete" value: finished];
    //  Save the data and cursor in one document. The backup contains the matching previous pair.
    success = [previous WriteFile: backupPath];
    if (success != YES) {
        NSLog(@"%@",@"Could not back up the previous checkpoint; no replacement attempted.");
        return;
    }

    success = [state WriteFile: cachePath];
    if (success != YES) {
        NSLog(@"%@",@"Checkpoint write failed. Restore the private .bak before continuing.");
        return;
    }

    pageCount = pageCount + 1;
    if (finished == YES) {
        NSLog(@"%@",@"Synchronization round complete; saved the delta link for the next run.");
        return;
    }

}

NSLog(@"%@",@"Paused after 100 pages; the saved nextLink resumes on the next run.");