Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.6.0+

OneDrive: Download a File to Disk

See more OneDrive Examples

GET /content can return HTTP 200 with file bytes directly, or HTTP 302 with a service URL. Handle both instead of requiring a redirect. Check transport completion and HTTP status, and compare Content-Length to the received byte count when supplied. Requests specify identity encoding; unexpected content encodings are rejected. A successful zero-byte file is valid. A 401 can mean an expired token, wrong audience, or expired preauthenticated URL; a 403 can indicate missing grants or policy restrictions.

Both the initial Graph request and any returned-URL request use HttpReq with Http.StreamResponseBodyPath to stream into a generated .part file. The redirect body is replaced by the actual content. Rename only after a complete HTTP 200 transfer, so errors and truncated responses never become the final file. A failed transfer may leave a private .part file for cleanup. The file content is not buffered in memory and supplied remote filenames are not used as local paths.

Returned service URLs are used unchanged with automatic redirects disabled. Graph URLs on graph.microsoft.com:443 use the Graph token. A separate SharePoint token is sent only to the exact configured host on port 443. Legacy URLs carrying tempauth are used without a bearer token, even when a SharePoint cache exists. Other content hosts receive no bearer token. HTTPS and absence of embedded login credentials are checked. Unexpected redirects stop rather than forwarding credentials.

For authenticated SharePoint transfers, prepare private qa_data/tokens/oneDrive-sharepoint.json containing host (a bare trusted hostname, such as tenant.sharepoint.com) and access_token issued for that SharePoint resource. Keep it separate from the Graph token cache. The app must obtain consent and acquire/refresh the SharePoint token separately; these transfer examples do not do that automatically. Use the appropriate tenant/resource/account and current permissions. On 401, renew the appropriate token or obtain a fresh legacy URL; do not blindly retry a write or forward the Graph token to SharePoint.

See the OneDrive guide: transfer authentication and Microsoft's current returned-URL behavior.

Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.

Permission: Files.Read.

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 Swift Downloads

Swift

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))
    endpoint.append(value: "/content")
    http.setRequestHeader(name: "Accept", value: "*/*")
    http.setRequestHeader(name: "Accept-Encoding", value: "identity")
    let fac = CkoFileAccess()!
    success = fac.dirEnsureExists(dirPath: "qa_output/oneDrive")
    if success != true {
        print("Could not create the output directory.")
        return
    }

    let uuid = CkoCrypt2()!
    var localId: String? = uuid.generateUuid()
    if uuid.lastMethodSuccess != true {
        print("Could not make a local filename.")
        return
    }

    let target = CkoStringBuilder()!
    target.append(value: "qa_output/oneDrive/")
    target.append(value: localId)
    target.append(value: ".bin")
    var finalPath: String? = target.getAsString()
    target.append(value: ".part")
    var partialPath: String? = target.getAsString()
    if fac.fileExists(path: finalPath) || fac.fileExists(path: partialPath) {
        print("A generated output path already exists; nothing overwritten.")
        return
    }

    //  Stream even the initial Graph response; direct content can be arbitrarily large.
    let streamRequest = CkoHttpRequest()!
    streamRequest.httpVerb = "GET"
    http.streamResponseBodyPath = partialPath
    success = http.httpReq(url: endpoint.getAsString(), request: streamRequest, response: resp)
    http.streamResponseBodyPath = ""
    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 != 302) {
        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
    }

    if resp.statusCode.intValue == 302 {
        var downloadUrl: String? = resp.getHeaderField(fieldName: "Location")
        let serviceUrl = CkoUrl()!
        success = serviceUrl.parse(url: downloadUrl)
        if success != true {
            print("Invalid returned service URL.")
            return
        }

        if (serviceUrl.ssl != true) || (serviceUrl.host == "") || (serviceUrl.login != "") || (serviceUrl.password != "") {
            print("Expected an HTTPS service URL without embedded login credentials.")
            return
        }

        //  Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
        //  Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
        let downloadHttp = CkoHttp()!
        downloadHttp.requireSslCertVerify = true
        downloadHttp.followRedirects = false
        downloadHttp.connectTimeout = 20
        downloadHttp.readTimeout = 120
        let serviceHost = CkoStringBuilder()!
        serviceHost.append(value: serviceUrl.host)
        let serviceQuery = CkoStringBuilder()!
        serviceQuery.append(value: serviceUrl.query)
        let authMatch = CkoJsonObject()!
        var authMatched: Int = serviceQuery.regexMatch(pattern: "(?i)(?:^|[?&])tempauth=[^&]+", json: authMatch, timeoutMs: 100).intValue
        if authMatched < 0 {
            print("Could not inspect the service URL query.")
            return
        }

        //  tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
        if authMatched == 0 {
            if (serviceHost.contentsEqual(str: "graph.microsoft.com", caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
                downloadHttp.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
                    }

                    //  Configure host independently; never trust a response URL to choose a new credential audience.
                    if (serviceHost.contentsEqual(str: sharepointToken.string(of: "host"), caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
                        downloadHttp.authToken = sharepointToken.string(of: "access_token")
                    }

                }

            }

        }

        //  Without a matching token, only a still-valid preauthenticated URL can succeed.
        downloadHttp.setRequestHeader(name: "Accept", value: "*/*")
        downloadHttp.setRequestHeader(name: "Accept-Encoding", value: "identity")
        //  The second response overwrites the temporary redirect body; it is not appended.
        downloadHttp.streamResponseBodyPath = partialPath
        success = downloadHttp.httpReq(url: downloadUrl, request: streamRequest, response: resp)
        downloadHttp.streamResponseBodyPath = ""
        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) {
            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
        }

    }

    //  A partial transfer can have status 200 but a false transport result. Never publish its bytes.
    if success != true {
        print("Content transfer did not complete; do not use its partial data.")
        return
    }

    var actualSize: String? = fac.fileSizeStr(filePath: partialPath)
    if fac.lastMethodSuccess != true {
        print("Could not determine the downloaded file size.")
        return
    }

    //  Ask for identity encoding so Content-Length can be compared to the stored file bytes.
    let contentEncoding = CkoStringBuilder()!
    contentEncoding.append(value: resp.getHeaderField(fieldName: "Content-Encoding"))
    contentEncoding.trim()
    if (contentEncoding.length.intValue > 0) && (contentEncoding.contentsEqual(str: "identity", caseSensitive: false) != true) {
        print("Unexpected content encoding; do not use this response as the file.")
        return
    }

    let declaredLength = CkoStringBuilder()!
    declaredLength.append(value: resp.getHeaderField(fieldName: "Content-Length"))
    declaredLength.trim()
    if declaredLength.length.intValue > 0 {
        let lengthMatch = CkoJsonObject()!
        var lengthMatched: Int = declaredLength.regexMatch(pattern: "\\A[0-9]+\\z", json: lengthMatch, timeoutMs: 100).intValue
        if lengthMatched != 1 {
            print("Invalid Content-Length; do not use this response as the file.")
            return
        }

        //  Compare decimal strings rather than narrowing a large file length to int.
        while ((declaredLength.length.intValue > 1) && (declaredLength.starts(with: "0", caseSensitive: true) == true)) {
            declaredLength.removeChars(at: 0, numChars: 1)
        }

        if declaredLength.contentsEqual(str: actualSize, caseSensitive: true) != true {
            print("Content transfer did not complete: byte count differs from Content-Length.")
            return
        }

    }

    success = fac.fileRename(existingPath: partialPath, newPath: finalPath)
    if success != true {
        print("Download completed but final rename failed; retain the .part file.")
        return
    }

    print("Saved file: \(finalPath!)")

}