Posted by Leah Culver on September 09, 2014
Swift is a new programming language for iOS and OS X with a modern syntax. Swift is fast and powerful and it's easy to see why Swift is gaining popularity amongst developers.
We're happy to say that you can use any of the Dropbox SDKs for iOS/OS X in your Swift app. Let's take a look at using the iOS Sync SDK in Swift.
To get started, you'll need to follow the iOS Sync SDK installation instructions. Since the SDK is built in Objective-C, there's one extra step.
Create an Objective-C file called Temp.m, which will signal to Xcode that you're using Objective-C in your project. Xcode will then prompt you to add a bridging header. Click "yes" and add the following line to the file:
#import <Dropbox/Dropbox.h>
That's all you need to do! If you want, you can delete the Temp.m file, which you no longer need.
Now that you've imported Dropbox in your bridging header, you can start using Dropbox in your app. Let's link to Dropbox, just like the first step in the Sync API tutorial.
AppDelegate.swift
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let accountManager = DBAccountManager(appKey: "APP_KEY", secret: "APP_SECRET")
DBAccountManager.setSharedManager(accountManager)
return true
}
(Be sure to replace APP_KEY and APP_SECRET with the real values for your app which could be found in the App Console.)
Next you'll need to link the user's account. For this example, assume we have a "Link with Dropbox" button that we connected in Interface Builder to this function:
ViewController.swift
@IBAction func didPressLink(sender: AnyObject) {
DBAccountManager.sharedManager().linkFromController(self)
}
Finally, your app will need to respond to a redirect from Dropbox to complete the authorization flow:
AppDelegate.swift
func application(application: UIApplication, openURL url: NSURL,
sourceApplication: String, annotation: AnyObject?) -> Bool {
let account = DBAccountManager.sharedManager().handleOpenURL(url)
if (account != nil) {
println("App linked successfully!")
return true
}
return false
}
Now the user is linked with Dropbox!
This is just a quick example of how to get started using the Dropbox Sync API in your Swift app. Give it a try and let us know if you have any questions on our developer forum.