Swift
Swift
Facebook Download all Photos to Local Files
See more Facebook Examples
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 Swift Downloads
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 will use a local disk cache to avoid re-fetching the same
// photo id after it's been fetched once.
let fbCache = CkoCache()!
// The cache will use 1 level of 256 sub-directories.
fbCache.level = 1
// Use a directory path that makes sense on your operating system..
fbCache.addRoot(path: "C:/fbCache")
// 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)
// 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(name: "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(name: "limit", value: "100")
// Get the 1st page of photos ids.
// See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
var responseJson: String? = rest.fullRequestNoBody(httpVerb: "GET", uriPath: "/v2.7/me/photos")
if rest.lastMethodSuccess != true {
print("\(rest.lastErrorText!)")
return
}
let photoJson = CkoJsonObject()!
let saPhotoUrls = CkoStringArray()!
let sbPhotoIdPath = CkoStringBuilder()!
let json = CkoJsonObject()!
json.emitCompact = false
json.load(json: responseJson)
var i: Int
var photoId: String?
var imageUrl: String?
// Get the "after" cursor.
var afterCursor: String? = json.string(of: "paging.cursors.after")
while json.lastMethodSuccess == true {
print("-------------------")
print("afterCursor = \(afterCursor!)")
// For each photo id in this page...
i = 0
var numItems: Int = json.size(ofArray: "data").intValue
while i < numItems {
json.i = i
photoId = json.string(of: "data[i].id")
print("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.
var photoJsonStr: String? = fbCache.fetchText(key: photoId)
if fbCache.lastMethodSuccess == false {
// It's not locally available, so get it from Facebook..
sbPhotoIdPath.clear()
sbPhotoIdPath.append(value: "/v2.7/")
sbPhotoIdPath.append(value: photoId)
rest.clearAllQueryParams()
rest.addQueryParam(name: "fields", value: "id,album,images")
print("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(httpVerb: "GET", uriPath: sbPhotoIdPath.getAsString())
if rest.lastMethodSuccess != true {
print("\(rest.lastErrorText!)")
return
}
// Add the photo JSON to the local cache.
fbCache.saveTextNoExpire(key: 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(json: photoJsonStr)
imageUrl = photoJson.string(of: "images[0].source")
if photoJson.lastMethodSuccess == true {
// Actually, we'll add a small JSON document that contains both the image ID and the URL.
let imgUrlJson = CkoJsonObject()!
imgUrlJson.appendString(name: "id", value: photoId)
imgUrlJson.appendString(name: "url", value: imageUrl)
saPhotoUrls.append(str: imgUrlJson.emit())
print("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(name: "type", value: "uploaded")
rest.addQueryParam(name: "limit", value: "20")
rest.addQueryParam(name: "after", value: afterCursor)
// Get the next page of photo ids.
responseJson = rest.fullRequestNoBody(httpVerb: "GET", uriPath: "/v2.7/me/photos")
if rest.lastMethodSuccess != true {
print("\(rest.lastErrorText!)")
return
}
json.load(json: responseJson)
afterCursor = json.string(of: "paging.cursors.after")
}
print("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.
let http = CkoHttp()!
// We'll cache the image data so that if run again, we don't re-download the same image again.
var numUrls: Int = saPhotoUrls.count.intValue
i = 0
let urlJson = CkoJsonObject()!
var imageBytes: NSData
let fac = CkoFileAccess()!
while i < numUrls {
urlJson.load(json: saPhotoUrls.getString(index: i))
photoId = urlJson.string(of: "id")
imageUrl = urlJson.string(of: "url")
// Check the local cache for the image data.
// Only download and save if not already cached.
imageBytes = fbCache.fetch(fromCache: imageUrl)
if fbCache.lastMethodSuccess == false {
// This photo needs to be downloaded.
let sbImageUrl = CkoStringBuilder()!
sbImageUrl.append(value: imageUrl)
// Let's form a filename..
var extension: String? = ".jpg"
if sbImageUrl.contains(str: ".gif", caseSensitive: false) == true {
extension = ".gif"
}
if sbImageUrl.contains(str: ".png", caseSensitive: false) == true {
extension = ".png"
}
if sbImageUrl.contains(str: ".tiff", caseSensitive: false) == true {
extension = ".tiff"
}
if sbImageUrl.contains(str: ".bmp", caseSensitive: false) == true {
extension = ".bmp"
}
let sbLocalFilePath = CkoStringBuilder()!
sbLocalFilePath.append(value: "C:/Photos/facebook/uploaded/")
sbLocalFilePath.append(value: photoId)
sbLocalFilePath.append(value: extension)
imageBytes = http.quickGet(url: imageUrl)
if http.lastMethodSuccess != true {
print("\(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.save(toCacheNoExpire: imageUrl, eTag: "", data: imageBytes)
fac.writeEntireFile(path: sbLocalFilePath.getAsString(), fileData: imageBytes)
print("Downloaded to \(sbLocalFilePath.getAsString()!)")
}
i = i + 1
}
print("Finished downloading all Facebook photos!")
}