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

OneDrive: Copy a File or Folder and Monitor Completion

See more OneDrive Examples

Creates a new item: copy a selected item to an explicitly addressed destination folder. A folder copy includes its descendants. The first run submits the request and saves its monitor URL; subsequent runs make one status request without submitting another copy. Use a fresh private receipt for each intentional operation and account. Schedule checks with backoff and honor Retry-After; 202 means accepted, not finished.

The receipt starts as pending before submission. A lost response or failed write requires reconciling the destination before starting again. Completed and failed receipts prevent automatic resubmission. Monitoring accepts JSON completion and 303 completion responses without automatically following redirects. A resourceId, when returned, is the new item ID and stays a string. Monitor URLs can expire; they are private, temporary operation state.

The default conflict behavior fails on a name collision. Copies inherit destination permissions and do not retain all source metadata. This example copies current content only. Copying all versions requires includeAllVersionHistory=true; Microsoft documents a current issue when it is combined with name, so copy first without name and rename afterward for that workflow. Folder copies are limited to 30,000 items; app-only cross-geo copy is unsupported.

Microsoft has announced changes to preauthenticated URLs beginning April 1, 2027. The example supports Graph-hosted URLs with the Graph token and an explicitly configured SharePoint host with a separate SharePoint-audience token. A legacy preauthenticated URL is requested without a bearer token. Never forward the Graph token to a SharePoint or content host. If required, prepare private qa_data/tokens/oneDrive-sharepoint.json with host and access_token from a separately authorized SharePoint token acquisition; token refresh must preserve that audience. A 401 requires checking the correct token audience or URL expiry, not blindly adding credentials.

Permission: Files.ReadWrite.

Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.

For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoFileAccess.h>
#import <CkoUrl.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
//  Obtain a delegated Graph token with this example's file permissions.
//  See OneDrive OAuth2 with PKCE.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/oneDrive.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load the private OneDrive 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:120];
[http SetRequestHeader: @"Accept" value: @"application/json"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
NSString *driveId = @"YOUR_DRIVE_ID";
NSString *itemId = @"YOUR_ITEM_ID";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"https://graph.microsoft.com/v1.0/drives/"];
[endpoint Append: [http UrlEncode: driveId]];
[endpoint Append: @"/items/"];
[endpoint Append: [http UrlEncode: itemId]];
NSString *destinationDriveId = @"YOUR_DESTINATION_DRIVE_ID";
NSString *destinationFolderId = @"YOUR_DESTINATION_FOLDER_ID";
NSString *newName = @"copied-file.txt";
//  Use a separate private receipt for each copy operation and account.
NSString *accountKey = @"YOUR_LOCAL_ACCOUNT_KEY";
NSString *receiptPath = @"qa_data/oneDrive/copy-receipt.json";
CkoFileAccess *fac = [[CkoFileAccess alloc] init];
success = [fac DirEnsureExists: @"qa_data/oneDrive"];
if (success != YES) {
    NSLog(@"%@",@"Could not create the private receipt directory.");
    return;
}

CkoJsonObject *receipt = [[CkoJsonObject alloc] init];
receipt.Strict = YES;
if ([fac FileExists: receiptPath] == YES) {
    success = [receipt LoadFile: receiptPath];
    if (success != YES) {
        NSLog(@"%@",@"Invalid receipt; reconcile the existing operation before starting another.");
        return;
    }

    if ([receipt StringOfEquals: @"accountKey" value: accountKey caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"sourceDriveId" value: driveId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"sourceItemId" value: itemId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"destinationDriveId" value: destinationDriveId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"destinationFolderId" value: destinationFolderId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"name" value: newName caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Receipt belongs to another copy operation; no request sent.");
        return;
    }

    if ([receipt StringOfEquals: @"status" value: @"completed" caseSensitive: YES] == YES) {
        NSLog(@"%@%@",@"This copy already completed. Item ID: ",[receipt StringOf: @"resourceId"]);
        return;
    }

    if ([receipt StringOfEquals: @"status" value: @"failed" caseSensitive: YES] == YES) {
        NSLog(@"%@",@"The saved copy failed. Review its error and destination before starting another operation.");
        return;
    }

    if ([receipt StringOfEquals: @"status" value: @"monitoring" caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Copy outcome is uncertain; reconcile the destination before replacing this receipt.");
        return;
    }

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

}
else {
    [receipt UpdateString: @"accountKey" value: accountKey];
    [receipt UpdateString: @"sourceDriveId" value: driveId];
    [receipt UpdateString: @"sourceItemId" value: itemId];
    [receipt UpdateString: @"destinationDriveId" value: destinationDriveId];
    [receipt UpdateString: @"destinationFolderId" value: destinationFolderId];
    [receipt UpdateString: @"name" value: newName];
    //  Save intent before POST so a lost response cannot cause an automatic duplicate copy.
    [receipt UpdateString: @"status" value: @"pending"];
    success = [receipt WriteFile: receiptPath];
    if (success != YES) {
        NSLog(@"%@",@"Could not save the copy intent; nothing submitted.");
        return;
    }

    CkoJsonObject *body = [[CkoJsonObject alloc] init];
    [body UpdateString: @"parentReference.driveId" value: destinationDriveId];
    [body UpdateString: @"parentReference.id" value: destinationFolderId];
    [body UpdateString: @"name" value: newName];
    [endpoint Append: @"/copy"];
    //  Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
    success = [http HttpJson: @"POST" url: [endpoint GetAsString] json: body contentType: @"application/json" response: resp];
    if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
        NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
        return;
    }

    if (([resp.StatusCode intValue] != 202)) {
        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"]);
        }

        return;
    }

    NSString *monitorUrl = [resp GetHeaderField: @"Location"];
    if (monitorUrl == @"") {
        NSLog(@"%@",@"Accepted without a monitor URL; keep the pending receipt and reconcile the destination.");
        return;
    }

    [receipt UpdateString: @"monitorUrl" value: monitorUrl];
    [receipt UpdateString: @"status" value: @"monitoring"];
    success = [receipt WriteFile: receiptPath];
    if (success != YES) {
        NSLog(@"%@",@"Accepted, but receipt save failed. Do not repeat POST; reconcile the destination.");
        return;
    }

    NSLog(@"%@",@"Copy accepted. Run again later to check its status; honor Retry-After.");
    NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
    return;
}

//  One status request per run. The caller schedules the next run with backoff and Retry-After.
NSString *statusUrl = [receipt StringOf: @"monitorUrl"];
CkoUrl *serviceUrl = [[CkoUrl alloc] init];
success = [serviceUrl ParseUrl: statusUrl];
if (success != YES) {
    NSLog(@"%@",@"Invalid service URL.");
    return;
}

if ((serviceUrl.Ssl != YES) || (serviceUrl.Host == @"") || (serviceUrl.Login != @"") || (serviceUrl.Password != @"")) {
    NSLog(@"%@",@"Expected an HTTPS service URL without embedded login credentials.");
    return;
}

CkoHttp *monitorHttp = [[CkoHttp alloc] init];
monitorHttp.RequireSslCertVerify = YES;
monitorHttp.FollowRedirects = NO;
monitorHttp.ConnectTimeout = [NSNumber numberWithInt:20];
monitorHttp.ReadTimeout = [NSNumber numberWithInt:120];
CkoStringBuilder *serviceHost = [[CkoStringBuilder alloc] init];
[serviceHost Append: serviceUrl.Host];
if (([serviceHost ContentsEqual: @"graph.microsoft.com" caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
    monitorHttp.AuthToken = [token StringOf: @"access_token"];
}
else {
    CkoFileAccess *tokenFiles = [[CkoFileAccess alloc] init];
    if ([tokenFiles FileExists: @"qa_data/tokens/oneDrive-sharepoint.json"] == YES) {
        CkoJsonObject *sharepointToken = [[CkoJsonObject alloc] init];
        sharepointToken.Strict = YES;
        success = [sharepointToken LoadFile: @"qa_data/tokens/oneDrive-sharepoint.json"];
        if (success != YES) {
            NSLog(@"%@",@"Could not read the private SharePoint token cache.");
            return;
        }

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

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

        //  host is a configured exact hostname, not a URL and not obtained from the service response.
        if (([serviceHost ContentsEqual: [sharepointToken StringOf: @"host"] caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
            monitorHttp.AuthToken = [sharepointToken StringOf: @"access_token"];
        }

    }

}

//  With no matching token configured, only a still-valid preauthenticated URL can succeed.
success = [monitorHttp HttpNoBody: @"GET" url: statusUrl response: resp];
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
    NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
    return;
}

if (([resp.StatusCode intValue] != 200) && ([resp.StatusCode intValue] != 202) && ([resp.StatusCode intValue] != 303)) {
    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"]);
    }

    return;
}

BOOL completed = [resp.StatusCode intValue] == 303;
if (resp.BodyStr != @"") {
    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Invalid monitor JSON; keep the receipt and inspect the operation.");
        return;
    }

    if ([result StringOfEquals: @"status" value: @"completed" caseSensitive: NO] == YES) {
        completed = YES;
    }

    if ([result StringOfEquals: @"status" value: @"failed" caseSensitive: NO] == YES) {
        [receipt UpdateString: @"status" value: @"failed"];
        [receipt UpdateString: @"errorCode" value: [result StringOf: @"error.code"]];
        success = [receipt WriteFile: receiptPath];
        if (success != YES) {
            NSLog(@"%@",@"Could not save the failed-operation receipt.");
            return;
        }

        NSLog(@"%@%@",@"Copy failed: ",[result StringOf: @"error.code"]);
        return;
    }

}

if (completed == YES) {
    [receipt UpdateString: @"status" value: @"completed"];
    if ([[result JsonTypeOf: @"resourceId"] intValue] == 1) {
        [receipt UpdateString: @"resourceId" value: [result StringOf: @"resourceId"]];
    }

    success = [receipt WriteFile: receiptPath];
    if (success != YES) {
        NSLog(@"%@",@"Copy completed but the receipt could not be saved. Reconcile before another copy.");
        return;
    }

    NSLog(@"%@%@",@"Copy completed. Destination drive ID: ",destinationDriveId);
    NSLog(@"%@%@",@"New item ID, if returned: ",[receipt StringOf: @"resourceId"]);
    //  A 303 without a JSON resourceId still indicates completion. Look up the destination by name if needed.
    //  Do not follow Location/resourceLocation with the Graph bearer token automatically.
}
else {
    NSLog(@"%@%@",@"Copy not completed. Status: ",[result StringOf: @"status"]);
    NSLog(@"%@%@",@"Percent complete, if returned: ",[result StringOf: @"percentageComplete"]);
    NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
}