Try out SwiftyDropbox, the new Swift SDK for Dropbox API v2!

// By Leah Culver • May 19, 2015

[EDIT June 18, 2015] Sample code for linking a user was updated to show how to check if a user has already been authorized.

[EDIT June 3, 2015] This post has been updated to reflect the latest SwiftyDropbox SDK, v0.2.

We recently announced our new API v2, and now we're excited to bring you our first of many new SDKs for the new API... in Swift!

A lot of iOS apps integrate with Dropbox already, and we think Swift is the programming language of the future when it comes to building iOS apps.

SwiftyDropbox is an early preview of our Swift SDK for API v2, which helps you easily integrate Dropbox into your Swift app. In this blog post, we'll show you how to install SwiftyDropbox in your project and get started with a quick tutorial.

Please keep in mind that both the SwiftyDropbox SDK and API v2 are still just preview versions and may change in the coming months, so please don't use this SDK in production yet.

Let's get started!

Add the SwiftyDropbox SDK to your project using CocoaPods

You can either add the Dropbox Swift SDK to an existing project or create a new project in Xcode (just make sure you're using Xcode 6.3 or higher). First, you'll need to install the SwiftyDropbox SDK using CocoaPods.

1. Install CocoaPods:

sudo gem install cocoapods

2. If you've never used Cocoapods before, run:

pod setup

3. In your project directory, create a new file and call it "Podfile". Add the following text to the file:

platform :ios, '8.0'
use_frameworks!
   
pod 'SwiftyDropbox', :git => 'git@github.com:dropbox/SwiftyDropbox.git', :tag => '0.2'

4. From the project directory, install the SwiftyDropbox SDK with: 

pod install

You’ll see that both SwiftyDropbox and Alamofire were installed. If your project is open in Xcode, you’ll need to close it and re-open the project workspace (.xcworkspace file) in Xcode for everything to work properly.

Register a Dropbox API app

To use the Dropbox API, you'll need to register a new app in the App Console. Select Dropbox API app and choose your app's permission. You'll need to use the app key created with this app to access API v2. That's it! You're ready to start using SwiftyDropbox.

Link an account

Now that the SDK is installed, you'll need to create a DropboxAuthManager to handle linking a user's Dropbox account with your app. A good place to create this object is in your app delegate's application(_:didFinishLaunchingWithOptions:) method.

AppDelegate.swift

import UIKit
import SwiftyDropbox
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
 
    var window: UIWindow?
 
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
 
        Dropbox.setupWithAppKey("APP_KEY")
 
        return true
    }
}

Be sure to replace APP_KEY with the real app key for your app which can be found in the App Console.

The next step is to link a user’s account. Make this call from an action, such as a “Link to Dropbox” button in your app.

@IBAction func linkButtonPressed(sender: AnyObject) {
    if (Dropbox.authorizedClient == nil) {
        Dropbox.authorizeFromController(self)
    } else {
        print("User is already authorized!")
    }
}

Now when the user clicks your button to connect with Dropbox, an in-app web browser will be displayed for them to log in to Dropbox and authorize your app.

Once the user completes the authorization step, Dropbox will redirect them back to your app using a URL scheme.

Set up a URL scheme

1. In order to complete the authorization process, you'll need to add a unique URL scheme that Dropbox can call:

  • Click on your project in the Project Navigator, choose the Info tab, expand the URL Types section at the bottom, and press the + button.

  • In the URL Schemes enter db-APP_KEY (replacing APP_KEY with the key generated when you created your app).

2. You'll also need to add code to handle the URL scheme, in your app delegate.

AppDelegate.swift

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
     
    if let authResult = Dropbox.handleRedirectURL(url) {
        switch authResult {
        case .Success(let token):
            println("Success! User is logged into Dropbox.")
        case .Error(let error, let description):
            println("Error: \(description)")
        }
    }
 
    return false
}

Done! You can now run your app and test logging in with Dropbox.

Try some API requests

Now that your user is connected with a Dropbox account, you can try some API v2 calls using the SwiftyDropboxSDK!

ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
     
    // Verify user is logged into Dropbox
    if let client = Dropbox.authorizedClient {
     
        // Get the current user's account info
        client.usersGetCurrentAccount().response { response, error in
            if let account = response {
                println("Hello \(account.name.givenName)")
            } else {
                println(error!)
            }
        }
         
        // List folder
        client.filesListFolder(path: "").response { response, error in
            if let result = response {
                println("Folder contents:")
                for entry in result.entries {
                    println(entry.name)
                }
            } else {
                println(error!)
            }
        }
         
        // Upload a file
        let fileData = "Hello!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        client.filesUpload(path: "/hello.txt", body: fileData!).response { response, error in
            if let metadata = response {
                println("Uploaded file name: \(metadata.name)")
                println("Uploaded file revision: \(metadata.rev)")
                 
                // Get file (or folder) metadata
                client.filesGetMetadata(path: "/hello.txt").response { response, error in
                    if let metadata = response {
                        println("Name: \(metadata.name)")
                        if let file = metadata as? Files.FileMetadata {
                            println("This is a file.")
                            println("File size: \(file.size)")
                        } else if let folder = metadata as? Files.FolderMetadata {
                            println("This is a folder.")
                        }
                    } else {
                        println(error!)
                    }
                }
         
                // Download a file
                client.filesDownload(path: "/hello.txt").response { response, error in
                    if let (metadata, data) = response {
                        println("Dowloaded file name: \(metadata.name)")
                        println("Downloaded file data: \(data)")
                    } else {
                        println(error!)
                    }
                }
           
            } else {
                println(error!)
            }
        }
    }
}

You can find all currently available user methods in Users.swift and file methods in Files.swift.


// Copy link