business@innofied.com

US Toll-Free - +1 866 941 5117

Top
Screen-Shot-2014-05-01-at-5.45.04-PM

Integration of Dropbox in iOS applications

Introduction

Dropbox is used by millions of people for storing their files and other document safely. Many iOS applications need to connect to Dropbox to allow the user to access the files stored in their dropbox account.

In this blog I will demonstrate how to integrate Dropbox with any iOS applications and access the files in application itself.

Before you start, you will need a dropbox account. Create one for free right here with 2GB of storage, if you don’t have already.

Registering the application

Go to this linkand start registering your app.

The first choice to make is between “Drop-ins app” and “dropbox API app”. Make your proper choice and start with the detailing. To know the difference between “Drop-ins app” and “dropbox API app”, you can refer to this link

(I would like to go with “dropbox API app” as it is more robust and easy to integrate).

Then select whether your app should have full Dropbox access or if it only needs a folder within the user’s Dropbox. The choice entirely depends on the requirement.

After completing these two steps, you would receive an App key and an App secret key. These are important! Dropbox no longer allows direct login via username/password combination but uses oAuth to authenticate users. You will need the keys for authentication purpose.

1. Configuring your Xcode project

Now open a new Project or an existing one where you would integrate dropbox.

Download the Dropbox SDK for iOS from here.

Follow these steps:

  1. Open your project.

  2. Navigate to the SDK and drag the DropboxSDK.framework folder into your project in Xcode. Make sure “Copy items into destination group’s folder” is selected.

  3.  Ensure that you have the Security.framework added to your project. Click here to see how to add framework to a project

Now you are ready to start using the Dropbox SDK.

First we will authenticate and link your app with Dropbox.

2. Authentication

Add the following  header to your view controller.

#import <DropboxSDK/DropboxSDK.h>

Add the following set of codes to the function where you want to start linking your app to dropbox.

DBSession* dbSession = [[[DBSession alloc]
      initWithAppKey:@"APP_KEY"
      appSecret:@"APP_SECRET"
      root:ACCESS_TYPE] autorelease]; //remove autorealese if using ARC. 

[DBSession setSharedSession:dbSession];

Replace “APP_KEY” and “APP_SECRET”  with the app key and app secret key provided by dropbox while Registering the app. Set  “ACCESS_TYPE”  to  ”dropbox” .

For establishing a link and launching the authenticating process with dropbox, add following set of codes.

- (void)didPressLink {
    if (![[DBSession sharedSession] isLinked]) {
        [[DBSession sharedSession] linkFromController:self];
    }
}

3. Register your app

While authenticating your app, dropbox app will open if installed on your device or will open in Safari.  There the user will be prompted to login to their account. Once logged in and authenticated your app will launch again with the “URL Scheme db-App_Key”.

For registering to this scheme, open your Project-Info.plist File as “Source Code” and add following set of lines below first <dict> tag.

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>db-APP_KEY</string>
        </array>
    </dict>
</array>

Replace the “APP_KEY” with your app key without omitting the front “db-” or else your app will not be registered.

At last add the following function to your appDelegate 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;
}

Now run your project. Your app will close and either the Dropbox app or Safari should be launched . You can link your app to your Dropbox account. (Make sure you are logged in using the same email address you used to create the API keys) Once linked with Dropbox you should be redirected back to your app.

Now its time to start making API calls to access files in your dropbox account.

API calls

To access files from dropbox you need to create a DBRestClient object by implementing its getter method. Add the following set of code to your ViewController.m file where file accessing will be done.

- (DBRestClient *)restClient {
   if (!restClient) {
      restClient =
         [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
      restClient.delegate = self;
   }
   return restClient;
}

Note : “restClient” will be an object/property of DBRestClient in your ViewController.m file.

You can now access files in dropbox by making the following API call:

[[self restClient] loadMetadata:@"/"];

Note : In above function set path according to folder access. For example: Suppose in your root you have folder named ‘Test1’ inside which there is another folder ‘Test2’. Then to view the files in folder ‘Test2’ your path will be  “/Test1/Test2”

Add the following delegate methods that will allow you to access all files in a folder.

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);

Once you get to access the files you can do whatever you want from that collection. But for instance say, you don’t want the whole file, instead you want the file link .

Then you need to make the following API call that will give you the sharable link of file.

[self.restClient loadSharableLinkForFile:destPath];

For ‘destPath’ provide the file path as illustrated with file name appended at last like “filePath/yourFileName”.

Add the following delegate methods that will give you the file link.

-(void)restClient:(DBRestClient*)restClient loadedSharableLink:(NSString*)link forFile:(NSString*)path
{
    NSLog(@"Sharable link : %@",link);
}

-(void)restClient:(DBRestClient*)restClient loadSharableLinkFailedWithError:(NSError*)error
{
    NSLog(@"Error %@",error);
}

However, these links have some drawback. These short links created expire after a time.

For more details go to dropbox link and StackOverflow link.

You can find sample project for the above implementation in GitHub.

This is it. Hope it helps. Feel free to comment if you face any problem while integrating dropbox. Any suggestion for improvement will be appreciated.

Where to go from here

Now you have integrated Dropbox in your project. There are some other cloud services offering storage and they are quite popular too. Read Integration of Box in iOS applications and GoogleDrive Integration in iOS apps

Manish Kumar

Manish Kumar is an iOS developer at Kolkata, who enjoys building innovative applications. Besides he also loves playing football and listening to songs. He loves challenges and sharing his work in open source community. Lots of iOS objective C development work is going on in Innofied. You can reach us at contact@innofied.com

  • Pingback: Box Integration in iOS apps Innofied()

  • Pingback: Google Drive Integration in iOS apps Innofied()

  • Indieshack

    Manish, thanks very much for this writeup 🙂

    • Manish Kumar

      Thank you Indieshack for your appreciation

  • Mallikarjun Patil

    Hey ,

    Nice tutorial. I got a https://db.tt/Fa1p8Bw2 URL. It is a valid URL to a video. I am able to access the page, but how do I get the URL of video inside the page.

  • Manish Kumar

    Hey Mallikarjun, I don’t understand what do you mean by saying “how do I get the URL of video inside the page”.. Please explain.