Sample code for 30+ languages & platforms
Swift

Download Photo to a File

See more Facebook Examples

Assuming we have the ID of a Photo, this example demonstrates how to download the photo image data to a file.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example assumes a previously obtained an access token
    let oauth2 = CkoOAuth2()!
    oauth2.accessToken = "FACEBOOK-ACCESS-TOKEN"

    let rest = CkoRest()!

    // Connect to Facebook...
    success = rest.connect(hostname: "graph.facebook.com", port: 443, tls: true, autoReconnect: true)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    // Provide the authentication credentials (i.e. the access key)
    rest.setAuthOAuth2(authProvider: oauth2)

    // Assumes we've already obtained a Photo ID.
    var photoId: String? = "10210199026347451"

    let sbPath = CkoStringBuilder()!
    sbPath.append(value: "/v2.7/")
    sbPath.append(value: photoId)

    // First we're going to get the photo informaton so we can get the URL of the image file data.
    // Select the fields we want.
    // See https://developers.facebook.com/docs/graph-api/reference/photo/
    rest.addQueryParam(name: "fields", value: "id,album,images")

    var responseJson: String? = rest.fullRequestNoBody(httpVerb: "GET", uriPath: sbPath.getAsString())
    if rest.lastMethodSuccess != true {
        print("\(rest.lastErrorText!)")
        return
    }

    let json = CkoJsonObject()!
    json.emitCompact = false
    json.load(json: responseJson)

    // Show the JSON in human-readable format.
    print("\(json.emit()!)")

    // Get the image URL.
    var imageUrl: String? = json.string(of: "images[0].source")
    print("Downloading from \(imageUrl!)")

    let sbImageUrl = CkoStringBuilder()!
    sbImageUrl.append(value: imageUrl)

    // Build the output local file path.
    let sbToPath = CkoStringBuilder()!
    sbToPath.append(value: "qa_output/fb")
    sbToPath.append(value: json.string(of: "id"))
    var bCaseSensitive: Bool = false
    if sbImageUrl.contains(str: ".jpg", caseSensitive: bCaseSensitive) == true {
        sbToPath.append(value: ".jpg")
    }
    else {
        sbToPath.append(value: ".png")
    }

    print("Downloading to \(sbToPath.getAsString()!)")

    // Download using Chilkat HTTP.
    let http = CkoHttp()!
    success = http.download(url: imageUrl, saveToPath: sbToPath.getAsString())
    if success != true {
        print("\(http.lastErrorText!)")
    }
    else {
        print("Downloaded.")
    }


}