Setup with CocoaPods

SwiftyDropbox installs through CocoaPods and targets Xcode 6.3 or higher. You can add it to an existing project or start a fresh one. The SDK is an early preview of the Swift bindings for API v2, and both the SDK and the API may change, so it should not be used in production yet.

  1. Install CocoaPods:
sudo gem install cocoapods
  1. If you've never used CocoaPods before, run:
pod setup
  1. In your project directory, create a file named "Podfile" containing the following:
platform :ios, '8.0'
use_frameworks!
   
pod 'SwiftyDropbox', :git => '[email protected]:dropbox/SwiftyDropbox.git', :tag => '0.2'
  1. From the project directory, install the SDK:
pod install

The install pulls in both SwiftyDropbox and Alamofire. Close the project in Xcode and reopen the workspace (.xcworkspace) file before continuing.

App registration

API access requires an app registered in the App Console. Choose Dropbox API app, pick the permission your app needs, and note the generated app key — the SDK uses it to authenticate requests.

Linking a user account

Create a DropboxAuthManager to link a Dropbox account to your app; the app delegate's application(_:didFinishLaunchingWithOptions:) method is a suitable place for it. Substitute the app key from the App Console for APP_KEY.

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
    }
}

The account link itself is triggered from a user-facing action, such as a "Link to Dropbox" button.

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

Clicking that button opens an in-app browser where the user signs in to Dropbox and authorizes the app. Once authorized, Dropbox redirects back to your app via a URL scheme.

URL scheme configuration

  1. Register a scheme for Dropbox to call: select your project in the Project Navigator, open the Info tab, expand URL Types at the bottom, and click +. Under URL Schemes, enter db-APP_KEY, replacing APP_KEY with your app's key.
  2. Handle the incoming URL 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
}

Your app is now ready to run: launch it and log in with Dropbox to test the link flow.

Making API calls

With the account linked, API v2 calls are available through the SDK. Available user methods live in Users.swift, and file methods in Files.swift.

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!)
            }
        }
    }
}