Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Objective-C Web API Examples

Primary Categories

ABN AMRO
AWS Secrets Manager
AWS Security Token Service
AWS Translate
Activix CRM
Adyen
Alibaba Cloud OSS
Amazon Cognito
Amazon DynamoDB
Amazon MWS
Amazon Pay
Amazon Rekognition
Amazon SP-API
Amazon Voice ID
Aruba Fatturazione
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Backblaze S3
Banco Inter
Belgian eHealth Platform
Bitfinex v2 REST
Bluzone
BrickLink
Bunny CDN
CallRail
CardConnect
Cerved
ClickBank
Clickatell
Cloudfare
Constant Contact
DocuSign
Duo Auth MFA
ETrade
Ecwid
Egypt ITIDA
Egypt eReceipt
Etsy
Facebook
Faire
Frame.io
GeoOp
GetHarvest
Global Payments
Google People
Google Search Console
Google Translate
Google Vision
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
Jira
Lightspeed
MYOB
Magento
Mailgun

Mastercard
MedTunnel
MercadoLibre
MessageMedia
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Microsoft Teams
Moody's
Okta OAuth/OIDC
OneLogin OIDC
OneNote
OpenAI ChatGPT
PRODA
PayPal
Paynow.pl
Peoplevox
Populi
QuickBooks
Rabobank
Refinitiv
Royal Mail OBA
SCiS Schools Catalogue
SII Chile
SMSAPI
SOAP finkok.com
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
Trello
Twilio
Twitter API v2
Twitter v1
UPS
UniPin
VoiceBase
Vonage
WaTrend
Walmart v3
Wasabi
WhatsApp
WiX
WooCommerce
WordPress
Xero
Yahoo Mail
Yapily
Yousign
ZATCA
Zendesk
Zoom
_Miscellaneous_
eBay
effectconnect
hacienda.go.cr

 

 

 

(Objective-C) Facebook Download all Photos to Local Files

Demonstrates how to download all of one's Facebook photos to a local filesystem directory. This sample code keeps a local cache to avoid re-downloading the same photos twice. The program can be run again after a time, and it will download only photos that haven't yet been downloaded.

Chilkat Objective-C Library Downloads

MAC OS X (Cocoa) Libs

iOS Libs

#import <CkoCache.h>
#import <CkoOAuth2.h>
#import <CkoRest.h>
#import <NSString.h>
#import <CkoJsonObject.h>
#import <CkoStringArray.h>
#import <CkoStringBuilder.h>
#import <CkoHttp.h>
#import <CkoFileAccess.h>

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

// This example will use a local disk cache to avoid re-fetching the same
// photo id after it's been fetched once.
CkoCache *fbCache = [[CkoCache alloc] init];
// The cache will use 1 level of 256 sub-directories.
fbCache.Level = [NSNumber numberWithInt:1];
// Use a directory path that makes sense on your operating system..
[fbCache AddRoot: @"C:/fbCache"];

// This example assumes a previously obtained an access token
CkoOAuth2 *oauth2 = [[CkoOAuth2 alloc] init];
oauth2.AccessToken = @"FACEBOOK-ACCESS-TOKEN";

CkoRest *rest = [[CkoRest alloc] init];

// Connect to Facebook.
BOOL success = [rest Connect: @"graph.facebook.com" port: [NSNumber numberWithInt: 443] tls: YES autoReconnect: YES];
if (success != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

// Provide the authentication credentials (i.e. the access key)
[rest SetAuthOAuth2: oauth2];

// There are two choices:  
// We can choose to download the photos the person is tagged in or has uploaded
// by setting type to "tagged" or "uploaded".
[rest AddQueryParam: @"type" value: @"uploaded"];

// To download all photos, we begin with an outer loop that iterates over
// the list of photo nodes in pages.  Each page returned contains a list of 
// photo node ids.  Each photo node id must be retrieved to get the download URL(s)
// of the actual image.

// I don't know the max limit for the number of records that can be downloaded at once.
[rest AddQueryParam: @"limit" value: @"100"];

// Get the 1st page of photos ids.
// See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
NSString *responseJson = [rest FullRequestNoBody: @"GET" uriPath: @"/v2.7/me/photos"];
if (rest.LastMethodSuccess != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

CkoJsonObject *photoJson = [[CkoJsonObject alloc] init];
CkoStringArray *saPhotoUrls = [[CkoStringArray alloc] init];
CkoStringBuilder *sbPhotoIdPath = [[CkoStringBuilder alloc] init];

CkoJsonObject *json = [[CkoJsonObject alloc] init];
json.EmitCompact = NO;
[json Load: responseJson];

int i;
NSString *photoId = 0;
NSString *imageUrl = 0;

// Get the "after" cursor.
NSString *afterCursor = [json StringOf: @"paging.cursors.after"];
while (json.LastMethodSuccess == YES) {

    NSLog(@"%@",@"-------------------");
    NSLog(@"%@%@",@"afterCursor = ",afterCursor);

    // For each photo id in this page...
    i = 0;
    int numItems = [[json SizeOfArray: @"data"] intValue];
    while (i < numItems) {
        json.I = [NSNumber numberWithInt: i];
        photoId = [json StringOf: @"data[i].id"];
        NSLog(@"%@%@",@"photoId = ",photoId);

        // We need to fetch the JSON for this photo.  Check to see if it's in the local disk cache,
        // and if not, then get it from Facebook.
        NSString *photoJsonStr = [fbCache FetchText: photoId];
        if (fbCache.LastMethodSuccess == NO) {
            // It's not locally available, so get it from Facebook..
            [sbPhotoIdPath Clear];
            [sbPhotoIdPath Append: @"/v2.7/"];
            [sbPhotoIdPath Append: photoId];

            [rest ClearAllQueryParams];
            [rest AddQueryParam: @"fields" value: @"id,album,images"];

            NSLog(@"%@",@"Fetching photo node from Facebook...");

            // This REST request will continue using the existing connection.
            // If the connection was closed, it will automatically reconnect to send the request.
            photoJsonStr = [rest FullRequestNoBody: @"GET" uriPath: [sbPhotoIdPath GetAsString]];
            if (rest.LastMethodSuccess != YES) {
                NSLog(@"%@",rest.LastErrorText);
                return;
            }

            // Add the photo JSON to the local cache.
            [fbCache SaveTextNoExpire: photoId eTag: @"" strData: photoJsonStr];
        }

        // Parse the photo JSON and add the main photo download URL to saPhotoUrls
        // There may be multiple URLs in the images array, but the 1st one is the largest and main photo URL.
        // The others are smaller sizes of the same photo.
        [photoJson Load: photoJsonStr];
        imageUrl = [photoJson StringOf: @"images[0].source"];
        if (photoJson.LastMethodSuccess == YES) {

            // Actually, we'll add a small JSON document that contains both the image ID and the URL.
            CkoJsonObject *imgUrlJson = [[CkoJsonObject alloc] init];
            [imgUrlJson AppendString: @"id" value: photoId];
            [imgUrlJson AppendString: @"url" value: imageUrl];
            [saPhotoUrls Append: [imgUrlJson Emit]];
            NSLog(@"%@%@",@"imageUrl = ",imageUrl);
        }

        i = i + 1;
    }

    // Prepare for getting the next page of photos ids.
    // We can continue using the same REST object.
    // If already connected, we'll continue using the existing connection.
    // Otherwise, a new connection will automatically be made if needed.
    [rest ClearAllQueryParams];
    [rest AddQueryParam: @"type" value: @"uploaded"];
    [rest AddQueryParam: @"limit" value: @"20"];
    [rest AddQueryParam: @"after" value: afterCursor];

    // Get the next page of photo ids.
    responseJson = [rest FullRequestNoBody: @"GET" uriPath: @"/v2.7/me/photos"];
    if (rest.LastMethodSuccess != YES) {
        NSLog(@"%@",rest.LastErrorText);
        return;
    }

    [json Load: responseJson];
    afterCursor = [json StringOf: @"paging.cursors.after"];
}

NSLog(@"%@",@"No more pages of photos.");

// Now iterate over the photo URLs and download each to a file.
// We can use Chilkat HTTP.  No Facebook authorization (access token) is required to download
// the photo once the URL is known.  
CkoHttp *http = [[CkoHttp alloc] init];

// We'll cache the image data so that if run again, we don't re-download the same image again.
int numUrls = [saPhotoUrls.Count intValue];
i = 0;
CkoJsonObject *urlJson = [[CkoJsonObject alloc] init];
NSData imageBytes;
CkoFileAccess *fac = [[CkoFileAccess alloc] init];

while (i < numUrls) {
    [urlJson Load: [saPhotoUrls GetString: [NSNumber numberWithInt: i]]];
    photoId = [urlJson StringOf: @"id"];
    imageUrl = [urlJson StringOf: @"url"];

    // Check the local cache for the image data.
    // Only download and save if not already cached.
    imageBytes = [fbCache FetchFromCache: imageUrl];
    if (fbCache.LastMethodSuccess == NO) {
        //  This photo needs to be downloaded.

        CkoStringBuilder *sbImageUrl = [[CkoStringBuilder alloc] init];
        [sbImageUrl Append: imageUrl];

        // Let's form a filename..
        NSString *extension = @".jpg";
        if ([sbImageUrl Contains: @".gif" caseSensitive: NO] == YES) {
            extension = @".gif";
        }

        if ([sbImageUrl Contains: @".png" caseSensitive: NO] == YES) {
            extension = @".png";
        }

        if ([sbImageUrl Contains: @".tiff" caseSensitive: NO] == YES) {
            extension = @".tiff";
        }

        if ([sbImageUrl Contains: @".bmp" caseSensitive: NO] == YES) {
            extension = @".bmp";
        }

        CkoStringBuilder *sbLocalFilePath = [[CkoStringBuilder alloc] init];
        [sbLocalFilePath Append: @"C:/Photos/facebook/uploaded/"];
        [sbLocalFilePath Append: photoId];
        [sbLocalFilePath Append: extension];

        imageBytes = [http QuickGet: imageUrl];
        if (http.LastMethodSuccess != YES) {
            NSLog(@"%@",http.LastErrorText);
            return;
        }

        // We've downloaded the photo image bytes into memory.
        // Save it to the cache AND save it to the output file.
        [fbCache SaveToCacheNoExpire: imageUrl eTag: @"" data: imageBytes];
        [fac WriteEntireFile: [sbLocalFilePath GetAsString] fileData: imageBytes];

        NSLog(@"%@%@",@"Downloaded to ",[sbLocalFilePath GetAsString]);
    }

    i = i + 1;
}

NSLog(@"%@",@"Finished downloading all Facebook photos!");
 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.