Objective-C
Objective-C
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 Objective-C Downloads
#import <CkoOAuth2.h>
#import <CkoRest.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
BOOL success = NO;
// 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
CkoOAuth2 *oauth2 = [[CkoOAuth2 alloc] init];
oauth2.AccessToken = @"FACEBOOK-ACCESS-TOKEN";
CkoRest *rest = [[CkoRest alloc] init];
// Connect to Facebook...
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];
// Assumes we've already obtained a Photo ID.
NSString *photoId = @"10210199026347451";
CkoStringBuilder *sbPath = [[CkoStringBuilder alloc] init];
[sbPath Append: @"/v2.7/"];
[sbPath Append: 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: @"fields" value: @"id,album,images"];
NSString *responseJson = [rest FullRequestNoBody: @"GET" uriPath: [sbPath GetAsString]];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",rest.LastErrorText);
return;
}
CkoJsonObject *json = [[CkoJsonObject alloc] init];
json.EmitCompact = NO;
[json Load: responseJson];
// Show the JSON in human-readable format.
NSLog(@"%@",[json Emit]);
// Get the image URL.
NSString *imageUrl = [json StringOf: @"images[0].source"];
NSLog(@"%@%@",@"Downloading from ",imageUrl);
CkoStringBuilder *sbImageUrl = [[CkoStringBuilder alloc] init];
[sbImageUrl Append: imageUrl];
// Build the output local file path.
CkoStringBuilder *sbToPath = [[CkoStringBuilder alloc] init];
[sbToPath Append: @"qa_output/fb"];
[sbToPath Append: [json StringOf: @"id"]];
BOOL bCaseSensitive = NO;
if ([sbImageUrl Contains: @".jpg" caseSensitive: bCaseSensitive] == YES) {
[sbToPath Append: @".jpg"];
}
else {
[sbToPath Append: @".png"];
}
NSLog(@"%@%@",@"Downloading to ",[sbToPath GetAsString]);
// Download using Chilkat HTTP.
CkoHttp *http = [[CkoHttp alloc] init];
success = [http Download: imageUrl saveToPath: [sbToPath GetAsString]];
if (success != YES) {
NSLog(@"%@",http.LastErrorText);
}
else {
NSLog(@"%@",@"Downloaded.");
}