In this tutorial we will learn – how to integrate Dropbox with iOS applications. Let us take an example of iOS application. We will be talking about the following:
1. Uploading the files from iOS App to Dropbox
2. Downloading files from Dropbox
3. Browsing the Folder / Files structure of Dropbox.
There are mainly two types of APIs for Dropbox integration.
- Core API – For Uploading, downloading and browsing the file system
- Sync API – When there are some changes done in the files / folder then it will help in syncing-up to other devices.
Core API
Registering the application on Dropbox and linking in the App
1. Register Application with DropBox – To register your application with Dropbox , you need to go on Dropbox App Console and follow these steps.
- Select “Create App” on App Console.
- Select type of app and type of data which we want to save on dropbox .
- Give a unique name to your Application.
- Now your app created. It will give you “App key” and “AppSecret key”.
2. Linking iOS App with Dropbox – Download Dropbox SDK and add it your iOS Application. In info.plist URI scheme there is need of adding an item “db-APP_KEY”. In place of “APP KEY” we will put the App key which we get in first step. First you have to create the DBSession object for your app:
#import <DropboxSDK/DropboxSDK.h>
DBSession* dbSession =
[[[DBSession alloc]
initWithAppKey:@"APP_KEY" // add here app key
appSecret:@"APP_SECRET" // add here app secret key
root:ACCESS_TYPE] // either kDBRootAppFolder or kDBRootDropbox
autorelease];
[DBSession setSharedSession:dbSession];
Somewhere in your app add an event to launch the authentication process:
- (void)didPressLink {
if(![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] link];
}
}
Now, We need to add the following code to our application delegate in order to complete the authentication process.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL*)url {
if([[DBSession sharedSession] handleOpenURL:url]) {
if([[DBSession sharedSession] isLinked]) {
NSLog(@"App linked successfully!");
// At this point you can start making API calls
}
return YES;
}
// Add whatever other url handling code your app requires here
return NO;
}
Browse Folder and Files of Dropbox
All methods on DBRestClient are asynchronous, meaning they don’t immediately return the data they are meant to load. Each method has at least two corresponding DBRestClientDelegate methods, that get called when a request either succeeds or fails. We can list contents of folder by making the following call
[[self restClient] loadMetadata:@"/"];
The REST client will then call your delegate with one of the following callbacks:
- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {
if(metadata.isDirectory) {
NSLog(@"Folder '%@' contains:", metadata.path);
for(DBMetadata *file in metadata.contents) {
NSLog(@"t%@", file.filename);
}
}
}
- (void)restClient:(DBRestClient *)client
loadMetadataFailedWithError:(NSError*)error {
NSLog(@"Error loading metadata: %@", error);
}
Downloading file from Dropbox
Now that we know what files are available it’s time to download one.
[[self restClient] loadFile:dropboxPath intoPath:localPath]
To find out if the file download succeeds or fails you need to implement the following DBRestClientDelegatemethods:
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath {
NSLog(@"File loaded into path: %@", localPath);
}
- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error {
NSLog(@"There was an error loading the file - %@", error);
}
Uploading file to Dropbox
After Downloading we can do with it whatever we want. Now next chalenge is how we can upload a new file on dropbox to share it with other devices & people. Uploading is as simple as downloading:
NSString *localPath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
NSString *filename = @"Info.plist";
NSString *destDir = @"/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:localPath];
To see all the operations that are available and the corresponding callback methods look at the DBRestClient.h file in the SDK. Here are the delegate methods that you should implement to get the results of the upload call:
-(void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
NSLog(@"File uploaded successfully to path: %@", metadata.path);
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
NSLog(@"File upload failed with error - %@", error);
}
Sync API
The Sync API takes care of syncing all your data with Dropbox through a familiar, file system-like interface. It’s like giving your app its own, private Dropbox client. Here we can proceed with the same steps of linking account as in case of core API. Once app is linked we can create a file system object.
Syncing of account mainly needs when any change in Dropbox data need to update in all linking devices & people. So we have to implement the “Change Observer” in the program.
Observing Changes – A DBFile object is created and is associated with a specific version of that file. You can check whether it is cached and can be read immediately by using the status property. If it is not cached, the -readString: call will wait while it downloads. If you don’t want to wait, you can use an observer to track its download progress.
DBFileStatus *status = file.status;
if (!status.cached) {
[self.file addObserver:self block:^() {
// Check file.status and read if it's ready
}];
// Check if the status.cached is now YES to ensure nothing
// was missed while adding the observer
}
You can also check if the version you have is the most recent version of the file with its newerStatus property. If the file is the latest version, this will be nil. If not, it will return the sync status for the newest version of the file. When a file is open, the Sync API will automatically download newer versions of the file as they are available and newerStatus will include the download progress. Once a newer version is downloaded, newerStatus.cached will be set. Then you can call -[DBFile update:] to update the open file to the newest version.
In addition to a single file, you can also listen to changes to all files in a folder by using the [DBFilesystem addObserver:forPathAndChildren:] method.