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.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
let token = CkoJsonObject()!
token.strict = true
success = token.loadFile(path: "qa_data/tokens/oneDrive.json")
if success != true {
print("Could not load the private OneDrive token cache.")
return
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty access_token in the JSON.")
return
}
let http = CkoHttp()!
http.authToken = token.string(of: "access_token")
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 120
http.setRequestHeader(name: "Accept", value: "application/json")
let resp = CkoHttpResponse()!
let result = CkoJsonObject()!
result.strict = true
var driveId: String? = "YOUR_DRIVE_ID"
var itemId: String? = "YOUR_ITEM_ID"
let endpoint = CkoStringBuilder()!
endpoint.append(value: "https://graph.microsoft.com/v1.0/drives/")
endpoint.append(value: http.urlEncode(str: driveId))
endpoint.append(value: "/items/")
endpoint.append(value: http.urlEncode(str: itemId))
var destinationDriveId: String? = "YOUR_DESTINATION_DRIVE_ID"
var destinationFolderId: String? = "YOUR_DESTINATION_FOLDER_ID"
var newName: String? = "copied-file.txt"
// Use a separate private receipt for each copy operation and account.
var accountKey: String? = "YOUR_LOCAL_ACCOUNT_KEY"
var receiptPath: String? = "qa_data/oneDrive/copy-receipt.json"
let fac = CkoFileAccess()!
success = fac.dirEnsureExists(dirPath: "qa_data/oneDrive")
if success != true {
print("Could not create the private receipt directory.")
return
}
let receipt = CkoJsonObject()!
receipt.strict = true
if fac.fileExists(path: receiptPath) == true {
success = receipt.loadFile(path: receiptPath)
if success != true {
print("Invalid receipt; reconcile the existing operation before starting another.")
return
}
if receipt.string(ofEquals: "accountKey", value: accountKey, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "sourceDriveId", value: driveId, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "sourceItemId", value: itemId, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "destinationDriveId", value: destinationDriveId, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "destinationFolderId", value: destinationFolderId, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "name", value: newName, caseSensitive: true) != true {
print("Receipt belongs to another copy operation; no request sent.")
return
}
if receipt.string(ofEquals: "status", value: "completed", caseSensitive: true) == true {
print("This copy already completed. Item ID: \(receipt.string(of: "resourceId")!)")
return
}
if receipt.string(ofEquals: "status", value: "failed", caseSensitive: true) == true {
print("The saved copy failed. Review its error and destination before starting another operation.")
return
}
if receipt.string(ofEquals: "status", value: "monitoring", caseSensitive: true) != true {
print("Copy outcome is uncertain; reconcile the destination before replacing this receipt.")
return
}
if (receipt.jsonType(of: "monitorUrl").intValue != 1) || (receipt.string(ofEquals: "monitorUrl", value: "", caseSensitive: true) == true) {
print("Expected a nonempty monitorUrl in the JSON.")
return
}
}
else {
receipt.updateString(jsonPath: "accountKey", value: accountKey)
receipt.updateString(jsonPath: "sourceDriveId", value: driveId)
receipt.updateString(jsonPath: "sourceItemId", value: itemId)
receipt.updateString(jsonPath: "destinationDriveId", value: destinationDriveId)
receipt.updateString(jsonPath: "destinationFolderId", value: destinationFolderId)
receipt.updateString(jsonPath: "name", value: newName)
// Save intent before POST so a lost response cannot cause an automatic duplicate copy.
receipt.updateString(jsonPath: "status", value: "pending")
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Could not save the copy intent; nothing submitted.")
return
}
let body = CkoJsonObject()!
body.updateString(jsonPath: "parentReference.driveId", value: destinationDriveId)
body.updateString(jsonPath: "parentReference.id", value: destinationFolderId)
body.updateString(jsonPath: "name", value: newName)
endpoint.append(value: "/copy")
// Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
success = http.httpJson(verb: "POST", url: endpoint.getAsString(), json: body, contentType: "application/json", response: resp)
if (success != true) && (resp.statusCode.intValue == 0) {
print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
return
}
if (resp.statusCode.intValue != 202) {
print("Unexpected HTTP status: \(resp.statusCode.intValue)")
print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
if resp.statusCode.intValue == 429 {
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
return
}
var monitorUrl: String? = resp.getHeaderField(fieldName: "Location")
if monitorUrl == "" {
print("Accepted without a monitor URL; keep the pending receipt and reconcile the destination.")
return
}
receipt.updateString(jsonPath: "monitorUrl", value: monitorUrl)
receipt.updateString(jsonPath: "status", value: "monitoring")
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Accepted, but receipt save failed. Do not repeat POST; reconcile the destination.")
return
}
print("Copy accepted. Run again later to check its status; honor Retry-After.")
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
return
}
// One status request per run. The caller schedules the next run with backoff and Retry-After.
var statusUrl: String? = receipt.string(of: "monitorUrl")
let serviceUrl = CkoUrl()!
success = serviceUrl.parse(url: statusUrl)
if success != true {
print("Invalid service URL.")
return
}
if (serviceUrl.ssl != true) || (serviceUrl.host == "") || (serviceUrl.login != "") || (serviceUrl.password != "") {
print("Expected an HTTPS service URL without embedded login credentials.")
return
}
let monitorHttp = CkoHttp()!
monitorHttp.requireSslCertVerify = true
monitorHttp.followRedirects = false
monitorHttp.connectTimeout = 20
monitorHttp.readTimeout = 120
let serviceHost = CkoStringBuilder()!
serviceHost.append(value: serviceUrl.host)
if (serviceHost.contentsEqual(str: "graph.microsoft.com", caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
monitorHttp.authToken = token.string(of: "access_token")
}
else {
let tokenFiles = CkoFileAccess()!
if tokenFiles.fileExists(path: "qa_data/tokens/oneDrive-sharepoint.json") == true {
let sharepointToken = CkoJsonObject()!
sharepointToken.strict = true
success = sharepointToken.loadFile(path: "qa_data/tokens/oneDrive-sharepoint.json")
if success != true {
print("Could not read the private SharePoint token cache.")
return
}
if (sharepointToken.jsonType(of: "host").intValue != 1) || (sharepointToken.string(ofEquals: "host", value: "", caseSensitive: true) == true) {
print("Expected a nonempty host in the JSON.")
return
}
if (sharepointToken.jsonType(of: "access_token").intValue != 1) || (sharepointToken.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("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(str: sharepointToken.string(of: "host"), caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
monitorHttp.authToken = sharepointToken.string(of: "access_token")
}
}
}
// With no matching token configured, only a still-valid preauthenticated URL can succeed.
success = monitorHttp.httpNoBody(verb: "GET", url: statusUrl, response: resp)
if (success != true) && (resp.statusCode.intValue == 0) {
print("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) {
print("Unexpected HTTP status: \(resp.statusCode.intValue)")
print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
if resp.statusCode.intValue == 429 {
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
return
}
var completed: Bool = resp.statusCode.intValue == 303
if resp.bodyStr != "" {
success = result.load(json: resp.bodyStr)
if success != true {
print("Invalid monitor JSON; keep the receipt and inspect the operation.")
return
}
if result.string(ofEquals: "status", value: "completed", caseSensitive: false) == true {
completed = true
}
if result.string(ofEquals: "status", value: "failed", caseSensitive: false) == true {
receipt.updateString(jsonPath: "status", value: "failed")
receipt.updateString(jsonPath: "errorCode", value: result.string(of: "error.code"))
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Could not save the failed-operation receipt.")
return
}
print("Copy failed: \(result.string(of: "error.code")!)")
return
}
}
if completed == true {
receipt.updateString(jsonPath: "status", value: "completed")
if result.jsonType(of: "resourceId").intValue == 1 {
receipt.updateString(jsonPath: "resourceId", value: result.string(of: "resourceId"))
}
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Copy completed but the receipt could not be saved. Reconcile before another copy.")
return
}
print("Copy completed. Destination drive ID: \(destinationDriveId!)")
print("New item ID, if returned: \(receipt.string(of: "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 {
print("Copy not completed. Status: \(result.string(of: "status")!)")
print("Percent complete, if returned: \(result.string(of: "percentageComplete")!)")
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
}